TopCoder.com Algorithm Problems Searcher



Found 500 results

ImpossibleGame

Graph Theory



Used in:

SRM 499

Used as:

Division I Level Three

Writer:

lyrically

Testers:

PabloGilberto , ivan_metelsky , nika

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11326

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14428&pm=11326

Problem Statement

    You are creating a simple one-player computer game. The player must first choose and enter a string of length k, where each character is 'A', 'B', 'C' or 'D'. Each possible string of length k maps to a color, and these mappings will be predetermined by you. To win the game, the player must perform a series of transformations on the string until it is different from the original, but maps to the same color. Only the following two transformations are allowed at each step:
  1. Swap two adjacent characters.
  2. Replace an occurrence of before[i] in the string with after[i], for some index i.
You want to create an "Impossible Mode", in which the player can never win. Return the minimum number of colors required to make the game impossible.
 

Definition

    
Class:ImpossibleGame
Method:getMinimum
Parameters:int, String[], String[]
Returns:long
Method signature:long getMinimum(int k, String[] before, String[] after)
(be sure your method is public)
    
 

Constraints

-k will be between 1 and 30, inclusive.
-before will contain between 1 and 50 elements, inclusive.
-before and after will contain the same number of elements.
-Each element of before will contain between 1 and k characters, inclusive.
-For each index i, before[i] and after[i] will contain the same number of characters.
-Each character in before and after will be 'A', 'B', 'C' or 'D'.
 

Examples

0)
    
1
{ "A" }
{ "B" }
Returns: 2
If "A" and "B" are assigned the same color, the player can win by starting with "A" and replacing it with "B". So at least two colors are needed.



Two colors are enough to make the game impossible. For example, you can assign red to "A" and "C", and blue to "B" and "D".
1)
    
2
{ "A", "A", "D" }
{ "B", "C", "D" }
Returns: 5
2)
    
2
{ "B", "C", "D" }
{ "C", "D", "B" }
Returns: 9
3)
    
6
{ "AABBC", "AAAADA", "AAACA", "CABAA", "AAAAAA", "BAAAA" }
{ "AACCB", "DAAABC", "AAAAD", "ABCBA", "AABAAA", "AACAA" }
Returns: 499

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

OneDimensionalBalls

Graph Theory, Simple Math, Simple Search, Iteration



Used in:

SRM 496

Used as:

Division I Level Two

Writer:

gojira_tc

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11318

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14425&pm=11318

Problem Statement

    There is an infinite axis with N balls on it. The balls are moving with equal positive velocity, some of them in the positive direction of the axis and some in the opposite. The balls are small enough to be treated as points on the axis. If two balls meet at a point, they do not collide, and instead, they each continue moving in the same direction and at the same speed as before.



Manao is shown a picture of the axis taken at some moment of time. All the balls are at different points in the picture. The balls are numbered from 0 to N-1 and the i-th ball is at point firstPicture[i].



Some time after the first picture is taken, several balls are added to the axis and another picture is taken. Yet again, no two balls share a point in this picture. The balls seem indistinguishable and their coordinates are given in int[] secondPicture in ascending order.



For each ball in the second picture, Manao has to guess whether it is present on the first one as well, and if so, say its number. Sometimes, this can't be determined unambiguously, so any valid guess is welcome. A guess is valid if the balls could move in the way described above and appear in the named locations in the second picture. Two guesses are different if there is a ball in the second picture which Manao identifies differently in these guesses. Return the number of valid guesses for the given pictures.
 

Definition

    
Class:OneDimensionalBalls
Method:countValidGuesses
Parameters:int[], int[]
Returns:long
Method signature:long countValidGuesses(int[] firstPicture, int[] secondPicture)
(be sure your method is public)
    
 

Constraints

-firstPicture will contain N elements, where N is between 1 and 50, inclusive.
-Each element of firstPicture will be between 0 and 100,000,000, inclusive.
-Elements in firstPicture will be distinct.
-secondPicture will contain between N and 50 elements, inclusive.
-Each element of secondPicture will be between 0 and 100,000,000, inclusive.
-Elements in secondPicture will be in strictly ascending order.
 

Examples

0)
    
{12,11}
{10,11,13}
Returns: 3
There are 2 balls in the first picture at points 12 and 11, respectively. One more ball is added in the second picture. The following three guesses are valid:

1) The ball at point 10 is ball 0, the ball at point 11 is the new one, the ball at point 13 is ball 1.

2) The ball at point 10 is ball 1, the ball at point 11 is ball 0, the ball at point 13 is the new one.

3) The ball at point 10 is ball 1, the ball at point 11 is the new one, the ball at point 13 is ball 0.

1)
    
{1,2,3}
{1,2,3}
Returns: 0
Each picture contains the same number of balls, so they must contain the same set of balls. However, given that some time has passed between the shots, and the balls move with equal positive velocity, there is no way for them to have interchanged positions.
2)
    
{1,3}
{1,3}
Returns: 1
If the balls move in opposite directions, they will interchange their positions at some moment.
3)
    
{7234}
{6316,689156,689160,689161,800000,1000001}
Returns: 6
Ball 0 could be any of the balls in the second picture.
4)
    
{6,2,4}
{1,2,3,4,5,7,8}
Returns: 7

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CarrotBoxes

Graph Theory



Used in:

SRM 495

Used as:

Division I Level Two

Writer:

rng_58

Testers:

PabloGilberto , ivan_metelsky , soul-net

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11304

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14424&pm=11304

Problem Statement

    There are N boxes numbered 0 through N-1. Every box except for one contains carrots, but Rabbit Hanako does not know which box is the empty one. Each box has the same probability of being empty.



Hanako wants to find the empty box without opening it. Fortunately, she has some clues. Some of the boxes contain information about the content of other boxes, and she knows which boxes contain such information. You are given a String[] information, where the j-th character of the i-th element is 'Y' if opening the i-th box will reveal whether or not the j-th box contains carrots, or 'N' if the i-th box contains no such information.



Return the probability that she can find the empty box without opening it, assuming she behaves optimally.
 

Definition

    
Class:CarrotBoxes
Method:theProbability
Parameters:String[]
Returns:double
Method signature:double theProbability(String[] information)
(be sure your method is public)
    
 

Constraints

-information will contain between 1 and 50 elements, inclusive.
-Each element of information will contain exactly N characters, where N is the number of elements of information.
-The i-th character of the i-th element of information will be 'Y'.
-Each character in information will be 'Y' or 'N'.
 

Examples

0)
    
{"YYYYY",
 "NYNNN",
 "NNYNN",
 "NNNYN",
 "NNNNY"}
Returns: 0.8
The optimal strategy is opening box 0 first. If box 0 contains carrots, she can find the empty box without opening it because box 0 contains information about all boxes. It happens with probability 0.8.
1)
    
{"YNNNN",
 "NYNNN",
 "NNYNN",
 "NNNYN",
 "NNNNY"}
Returns: 0.2
No box contains information about other boxes, so she can find the empty box without opening it only when she opens all other boxes. It happens with probability 0.2.
2)
    
{"Y"}
Returns: 1.0
Since there is only one box, she knows that the only box is empty.
3)
    
{"YNNNN",
 "YYNNN",
 "YNYNN",
 "NNNYY",
 "NNNYY"}
Returns: 0.6
4)
    
{"YYYNNNYN",
 "NYNNNNYN",
 "NNYNNNNN",
 "NYNYNNNN",
 "YNNNYNNY",
 "NNYNNYNN",
 "NNNNYNYN",
 "NNYNNNNY"}
Returns: 0.875
5)
    
{"YNNNNNNNNYNNNNNNNNNN",
 "NYNNNNNNNNNNNNNNNNNN",
 "NNYNNNNNNNYNNNNNYNNN",
 "NNNYNYNNNNNNNNYNNNNN",
 "NNNNYNNNNNNNNNYNNNNY",
 "NNNNNYNNNNNNNNNNNNNY",
 "NNNNYNYNYNNNNNNNNNNN",
 "NNNNNNNYNNNYYNNNNNNN",
 "NNNNNNNNYNNNNNNNNNNN",
 "YNNNNNNNNYNNNNNYNNNN",
 "NNNNNNNNNNYNNNNNNNNN",
 "NYNNNNNNNNNYNNNNNNNN",
 "NNNNNNNYNNNNYNNNNNNN",
 "NNNNNNNNNNNNNYNNNYNN",
 "NNNNNNNNNNNYNNYNNNYN",
 "NYNNNNNNNNNNNNNYNNNN",
 "NNYNNNNNNNNNNNNNYNNN",
 "NNNNNNNNNNNNNYNYNYNN",
 "NNNNNNNNYNYNNNNNNNYY",
 "NNNYNNNNNNNNNNNNNNNY"}
Returns: 0.75

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FoxCardGame

Graph Theory, Greedy, Simple Search, Iteration



Used in:

Member SRM 491

Used as:

Division I Level Three

Writer:

wrong

Testers:

Rustyoldman , ivan_metelsky , Mimino , rng_58

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11236

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14244&pm=11236

Problem Statement

    

Fox Jiro and Haruko play a game with two piles of cards: pile A and pile B. Pile A and pile B contain same number of cards. Each card contains a real number between 1.0 and 100.0. Initially, the two players have 0 points. Then they repeat following operations exactly k times:



  • They choose two cards from the piles (one from pile A and another from pile B).
  • The choosen cards are removed from the piles.
  • Jiro earns max{a+b, a*b} points and Haruko earns min{a+b, a*b} points (where a and b are the numbers written on the two cards that were removed).


You are given a double[] pileA, a double[] pileB, and an int k. Return the maximal possible value of (Jiro's points) / (Haruko's points).

 

Definition

    
Class:FoxCardGame
Method:theMaxProportion
Parameters:double[], double[], int
Returns:double
Method signature:double theMaxProportion(double[] pileA, double[] pileB, int k)
(be sure your method is public)
    
 

Notes

-The returned value must have an absolute or relative error less than 1e-9.
 

Constraints

-pileA and pileB will contain between 1 and 50 elements, inclusive.
-pileA and pileB will contain the same number of elements.
-Each element of pileA and pileB will be between 1.0 and 100.0, inclusive.
-k will be between 1 and the number of elements in pileA, inclusive.
 

Examples

0)
    
{1, 2, 3}
{4, 5, 6}
2
Returns: 1.7692307692307692
  1. Choosing cards with numbers 3 and 6, Jiro earns 3*6 = 18 points and Haruko earns 3+6 = 9 points.
  2. Choosing cards with numbers 1 and 4, Jiro earns 1+4 = 5 points and Haruko earns 1*4 = 4 points.

So the solution is (18+5) / (9+4) = 1.769230...

1)
    
{1.234, 5.678, 9.012, 3.456, 7.89}
{2.345, 6.789, 9.876, 5.432, 1.012}
3
Returns: 4.159424420079523
2)
    
{1, 1.1, 1.2, 1.3, 1.4, 1.5}
{5, 10, 15, 20, 25, 30}
2
Returns: 1.3972602739726028
3)
    
{85.302, 92.798, 76.813, 37.994, 36.737, 98.659}
{13.352, 7.3094, 54.761, 8.2706, 63.223, 37.486}
3
Returns: 33.58603889836175

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Hieroglyphs

Simple Search, Iteration



Used in:

SRM 490

Used as:

Division II Level Three

Writer:

Chmel_Tolstiy

Testers:

PabloGilberto , ivan_metelsky , pieguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11230

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14243&pm=11230

Problem Statement

    Hieroglyphs were widely used for writing in ancient times and they are used in some languages even now. In this problem, we will consider a simplified model of hieroglyphs.



Let's call a hieroglyph a two-dimensional figure that consists of several segments, each of which has a positive length and is either horizontal or vertical. The segments in the same hieroglyph can touch or intersect each other, but no two segments may overlap. That is, there are no two segments such that the length of their intersection is positive. The segments are considered to be infinitely thin.



You will be given two hieroglyphs in String[] hier1 and hier2. Both of them are drawn on the same plane with a Cartesian coordinate system. Each element of hier1 will be a comma-separated list of segments. Each segment is formatted "x1 y1 x2 y2" (quotes for clarity), where (x1, y1) and (x2, y2) are the coordinates of its two endpoints (x1 ≤ x2, y1 ≤ y2). The set of all segments of the first hieroglyph is the union of all segments presented in elements of hier1. The set of all segments of the second hieroglyph is given in the same format in elements of hier2. It is guaranteed that both hier1 and hier2 describe valid hieroglyphs as defined in the previous paragraph.



You are allowed to move each of the hieroglyphs to an arbitrary place on the plane via translation (See notes). No other operations like applying rotation or symmetry are allowed. Once the positions for each hieroglyph are chosen, their union is defined as a set of points on the plane that belong to at least one of them. It's easy to see that union of two hieroglyphs can be represented as a set of non-overlapping segments. You are to minimize the total length of these segments.



Return this minimum possible total length.
 

Definition

    
Class:Hieroglyphs
Method:minimumVisible
Parameters:String[], String[]
Returns:int
Method signature:int minimumVisible(String[] hier1, String[] hier2)
(be sure your method is public)
    
 

Notes

-Translation is an operation that moves every point a constant distance in a specified direction. More exactly, an arbitrary vector (dx, dy) is first chosen, and then translation works as moving each point (x, y) to (x + dx, y + dy).
 

Constraints

-hier1 and hier2 will each contain between 1 and 50 elements, inclusive.
-Each element of hier1 and hier2 will contain between 1 and 50 characters, inclusive.
-Each element of hier1 and hier2 will be a single comma separated list of between 1 and 4 segment descriptions, inclusive, without leading and trailing commas.
-Each segment description will be formatted "x1 y1 x2 y2" (quotes for clarity), where x1, y1, x2 and y2 are integers between 0 and 80, inclusive, with no extra leading zeros.
-In each segment description, x1 will be less than or equal to x2 and y1 will be less than or equal to y2.
-Each segment will be either horizontal or vertical and will have a positive length.
-No two segments of the same hieroglyph will overlap (as defined in the statement).
 

Examples

0)
    
{"0 0 10 0,10 0 10 3"}
{"0 1 10 1","5 1 5 4"}
Returns: 16


Here it's better to combine the horizontal line segments than the vertical ones.
1)
    
{"1 1 1 5"}
{"3 2 5 2"}
Returns: 6


There is no way to combine the hieroglyphs in such a way that segments overlap.
2)
    
{"0 2 6 2"}
{"5 1 6 1,8 1 9 1"}
Returns: 6
3)
    
{"10 20 10 30,15 20 15 30","10 20 15 20,0 30 30 30"}
{"0 5 0 15,5 5 5 25","0 5 5 5,0 15 5 15"}
Returns: 65
4)
    
{"10 10 10 20,10 30 10 40","10 10 20 10"}
{"10 0 10 20,10 27 10 35","10 0 20 0"}
Returns: 45

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

QuickT9

Dynamic Programming, String Manipulation



Used in:

SRM 490

Used as:

Division I Level Two

Writer:

Chmel_Tolstiy

Testers:

PabloGilberto , ivan_metelsky , pieguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11228

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14243&pm=11228

Problem Statement

    Most modern mobile phones include T9 technology for typing text messages faster, and your brand new mobile phone is not an exception.



Your mobile phone has the standard keyboard layout:

  Button     Letters
    2         a,b,c
    3         d,e,f
    4         g,h,i
    5         j,k,l
    6         m,n,o
    7        p,q,r,s
    8         t,u,v
    9        w,x,y,z
T9 requires a dictionary of words. At each moment, T9 maintains three strings: D -- the current combination of digits, F -- the "fixed" part of the message and U -- the "unfixed" part of the message. The message displayed on the phone's screen consists of the "fixed" part immediately followed by the "unfixed" part, i.e., it appears as F + U. The current combination of digits D is only stored in memory and not displayed. There always is the following correspondence between D and U: they have the same length and the i-th character in U is a letter written on the button with digit equal to the i-th character in D. Additionally, the string U must always be such that there's at least one word in the dictionary that starts with U. For a given combination of digits D, we will call a string U valid if it satisfies the described conditions.



When you start typing a new message, all three strings D, F and U are empty. Then you may do the following:
  • press one of the digit buttons (2-9): first, the pressed digit is added to the end of D, then U is changed to the lexicographically earliest string that is valid for the new value of D. If there are no such strings, the button press is ignored, so the values of D and U remain the same as before the button press.
  • press the Right button: first, U is appended to the end of F, then both D and U are reset to empty strings.
  • press the C button: U is appended to the end of F, then both D and U are reset to empty strings, finally, if F is not empty, the last character is removed from F.
  • press the * button: U is changed to the lexicographically next string valid for the current value of D. If there is no such string, it is set to the lexicographically smallest valid string again.
T9 technology is very useful when you need to type a message consisting of dictionary words. However there is a small drawback - typing a word that is not contained in the dictionary becomes much more difficult, so usually you have to type this word part by part (turning T9 off is not considered).



The problem you are facing now is to type a given word using T9. Return the smallest number of button presses needed to type this word on your mobile phone if it is possible at all, otherwise return -1. The word is considered to be typed if F is equal to the word and U is empty.



The dictionary is given in String[] t9. Each element of t9 is a list of words from the dictionary separated by single spaces.
 

Definition

    
Class:QuickT9
Method:minimumPressings
Parameters:String[], String
Returns:int
Method signature:int minimumPressings(String[] t9, String word)
(be sure your method is public)
    
 

Notes

-If two Strings A and B have the same length, then A comes before B lexicographically if it has an alphabetically earlier character at the first position where the Strings differ.
-It's possible that the dictionary contains multiple occurrences of the same word.
 

Constraints

-t9 will contain between 1 and 50 elements, inclusive.
-Each element of t9 will contain between 1 and 50 characters, inclusive.
-Each element of t9 will contain only lowercase letters ('a'-'z') and spaces, and will contain no leading, trailing or consecutive spaces.
-word will contain between 1 and 50 characters, inclusive.
-word will contain only lowercase letters ('a'-'z').
 

Examples

0)
    
{"aae", "bab", "abad", "bdbd", "beta"}
"babe"
Returns: 9
   Button  Result (the "unfixed" part of message in quotes)
1)   2      "a"          (beginning of "aae")
2)   2      "aa"         (beginning of "aae")
3)   2      "aba"        (beginning of "abad")
4)   *      "bab"        (beginning of "bab")
5)   C      ba
6)   2      ba"a"        (beginning of "aae")
7)   3      ba"bd"       (beginning of "bdbd")
8)   *      ba"be"       (beginning of "beta")
9) Right    babe
1)
    
{"ann","ie"}
"annie"
Returns: 7
   Button  Result (the "unfixed" part of message in quotes)
1)   2      "a"          (beginning of "ann")
2)   6      "an"         (beginning of "ann")
3)   6      "ann"        (beginning of "ann")
4) Right    ann
5)   4      ann"i"       (beginning of "ie")
6)   3      ann"ie"      (beginning of "ie")
7) Right    annie
2)
    
{"ann","amm"}
"annie"
Returns: -1
3)
    
{"aaa aab","aac aba abb ccca"}
"aba"
Returns: 6
   Button  Result (the "unfixed" part of message in quotes)
1)   2      "a"          (beginning of "aaa")
2)   2      "aa"         (beginning of "aaa")
3)   *      "ab"         (beginning of "aba")
4) Right    ab
5)   2      ab"a"        (beginning of "aaa")
6) Right    aba
4)
    
{"acac aba aaab","aab aa baa","bba bacade abb","baba"}
"abbaca"
Returns: 10
   Button  Result (the "unfixed" part of message in quotes)
1)   2      "a"          (beginning of "aa")
2)   2      "aa"         (beginning of "aa")
3)   *      "ab"         (beginning of "aba")
4) Right    ab
5)   2      ab"a"        (beginning of "aa")
6)   2      ab"aa"       (beginning of "aa")
7)   2      ab"aaa"      (beginning of "aaab")
8)   2      ab"aaab"     (beginning of "aaab")
9)   3      ab"bacad"    (beginning of "bacade")
10)  C      abbaca
5)
    
{"aaa aab aac","aba abb","ccca"}
"ccc"
Returns: 5

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheBoringGameDivOne

Advanced Math, Brute Force, Dynamic Programming, Encryption/Compression, Geometry, Graph Theory, Greedy, Math, Recursion, Search, Simple Math, Simple Search, Iteration, Simulation, Sorting, String Manipulation, String Parsing



Used in:

SRM 488

Used as:

Division I Level Three

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , ivan_metelsky , nika

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11205

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14241&pm=11205

Problem Statement

    John and Brus are very bored. That's why they decided to invite their friend and play a boring shooter game. John and Brus are on the first team and the friend is the only player of the second team. The game consists of X rounds. During a round players may shoot each other, but a player can't shoot himself. If a player shoots some player from the opposite team his score is increased by one and if he shoots his teammate his score is decreased by one. Once a player is shot, he can't shoot other players and other players can't shoot him until the end of the current round. A round ends when all the players on one of the teams are shot.



You are given six integers. scoreJ, scoreB and scoreF are scores of John, Brus and the friend respectively. killedJ, killedB and killedF are the number of times John, Brus and the friend were shot respectively. Return the int[] containing exactly two elements, where the first element is the smallest possible value of X and the second element is the largest possible value of X. If there are no possible values of X, return an empty int[].
 

Definition

    
Class:TheBoringGameDivOne
Method:find
Parameters:int, int, int, int, int, int
Returns:int[]
Method signature:int[] find(int scoreJ, int killedJ, int scoreB, int killedB, int scoreF, int killedF)
(be sure your method is public)
    
 

Constraints

-scoreJ will be between -1000 and 1000, inclusive.
-scoreB will be between -1000 and 1000, inclusive.
-scoreF will be between -1000 and 1000, inclusive.
-killedJ will be between 0 and 1000, inclusive.
-killedB will be between 0 and 1000, inclusive.
-killedF will be between 0 and 1000, inclusive.
 

Examples

0)
    
1
1
1
1
2
2
Returns: {2, 3 }
The possible scenario with two rounds is: friend kills John, Brus kills friend, round ends, friend kills Brus, John kills friend, round ends. And with three rounds - John kills friend, round ends, Brus kills friend, round ends, friend kills John, friend kills Brus, round ends.
1)
    
0
0
0
0
0
0
Returns: {0, 0 }
No rounds here.
2)
    
4
7
-2
5
1
9
Returns: { }
This is impossible.
3)
    
1
5
-1
4
3
6
Returns: {8, 9 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheBoringStoreDivTwo

Geometry, Graph Theory, String Manipulation



Used in:

SRM 488

Used as:

Division II Level Two

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , ivan_metelsky , nika

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11197

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14241&pm=11197

Problem Statement

    John and Brus are going to open a boring store. They would like to have a really boring name for it. John has one wooden plate with an old store name on it. Brus also has one.



Now they need to compose two plates with the same name (case-sensitive) for the new store. They would like to produce these new plates as follows:
  1. John will cut two pieces from his plate. Each of the pieces will contain a non-empty contiguous substring of the name written on the original plate and the locations of these two substrings within the plate will not overlap. For example, if the name on John's plate is "abCDeF", then he can cut pieces with "bC" and "e" or with "CDeF" and "ab", but he can't cut pieces with "aC" and "eF" ("aC" is not a contiguous substring), with "abCD" and "" (empty substring is not allowed) or with "DeF" and "CD" (locations of the substrings overlap). Let's denote the substrings on John's pieces as A and B.
  2. Brus will cut two pieces from his plate according to the same rules. Let's denote the substrings on these pieces as C and D.
  3. One plate for the new store will be constructed as A + C (where '+' means concatenation of two strings) and another plate will be constructed as B + D.
You are given two Strings J and B - the names on John's and Brus's plates respectively. Return the longest possible name for the new store that can be achieved as described above. In case of a tie choose the one that comes first lexicographically. If it is impossible to achieve the goal, return an empty String.
 

Definition

    
Class:TheBoringStoreDivTwo
Method:find
Parameters:String, String
Returns:String
Method signature:String find(String J, String B)
(be sure your method is public)
    
 

Notes

-If two Strings A and B have the same length, then A comes before B lexicographically if it has a smaller character at the first position where the Strings differ. When comparing the characters, refer to the following list of characters in ascending order: 'A', 'B', ..., 'Z', 'a', 'b', ..., 'z'.
 

Constraints

-J will contain between 1 and 15 characters, inclusive.
-B will contain between 1 and 15 characters, inclusive.
-Each character of J will be an uppercase or lowercase letter ('a' - 'z', 'A' - 'Z').
-Each character of B will be an uppercase or lowercase letter ('a' - 'z', 'A' - 'Z').
 

Examples

0)
    
"StoreOfJohn"
"StoreOfBrus"
Returns: "or"
John's plate contains two 'o's, and Brus's plate contains two 'r's, so one possible solution is for each new plate to contain one 'o' from John's plate and one 'r' from Brus's plate.
1)
    
"JohnAndJohn"
"John"
Returns: ""
The name on both new plates must end with a character from one of Brus's pieces. However, all characters on Brus's plate are different, so it is impossible to achieve the goal.
2)
    
"JohnPlaysGames"
"BrusAlsoPlays"
Returns: "ays"
3)
    
"abacaba"
"abacabadabacaba"
Returns: "abaabacaba"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheBoringStoreDivOne

Dynamic Programming, String Manipulation



Used in:

SRM 488

Used as:

Division I Level Two

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , ivan_metelsky , nika

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11196

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14241&pm=11196

Problem Statement

    John and Brus are going to open a boring store. They would like to have a really boring name for it. John has one wooden plate with an old store name on it. Brus also has one.



Now they need to compose two plates with the same name (case-sensitive) for the new store. They would like to produce these new plates as follows:
  1. John will cut two pieces from his plate. Each of the pieces will contain a non-empty contiguous substring of the name written on the original plate and the locations of these two substrings within the plate will not overlap. For example, if the name on John's plate is "abCDeF", then he can cut pieces with "bC" and "e" or with "CDeF" and "ab", but he can't cut pieces with "aC" and "eF" ("aC" is not a contiguous substring), with "abCD" and "" (empty substring is not allowed) or with "DeF" and "CD" (locations of the substrings overlap). Let's denote the substrings on John's pieces as A and B.
  2. Brus will cut two pieces from his plate according to the same rules. Let's denote the substrings on these pieces as C and D.
  3. One plate for the new store will be constructed as A + C (where '+' means concatenation of two strings) and another plate will be constructed as B + D.
You are given two Strings J and B - the names on John's and Brus's plates respectively. Return the longest possible name for the new store that can be achieved as described above. In case of a tie choose the one that comes first lexicographically. If it is impossible to achieve the goal, return an empty String.
 

Definition

    
Class:TheBoringStoreDivOne
Method:find
Parameters:String, String
Returns:String
Method signature:String find(String J, String B)
(be sure your method is public)
    
 

Notes

-If two Strings A and B have the same length, then A comes before B lexicographically if it has a smaller character at the first position where the Strings differ. When comparing the characters, refer to the following list of characters in ascending order: 'A', 'B', ..., 'Z', 'a', 'b', ..., 'z'.
 

Constraints

-J will contain between 1 and 47 characters, inclusive.
-B will contain between 1 and 47 characters, inclusive.
-Each character of J will be an uppercase or lowercase letter ('a' - 'z', 'A' - 'Z').
-Each character of B will be an uppercase or lowercase letter ('a' - 'z', 'A' - 'Z').
 

Examples

0)
    
"StoreOfJohn"
"StoreOfBrus"
Returns: "or"
John's plate contains two 'o's, and Brus's plate contains two 'r's, so one possible solution is for each new plate to contain one 'o' from John's plate and one 'r' from Brus's plate.
1)
    
"JohnAndJohn"
"John"
Returns: ""
The name on both new plates must end with a character from one of Brus's pieces. However, all characters on Brus's plate are different, so it is impossible to achieve the goal.
2)
    
"JohnLikesToPlayGames"
"BrusAlsoLikesToPlayGames"
Returns: "esToPlayGames"
3)
    
"abacaba"
"abacabadabacaba"
Returns: "abaabacaba"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SolitaireChess

Dynamic Programming, Graph Theory



Used in:

Member SRM 489

Used as:

Division II Level Three

Writer:

fushar

Testers:

liympanda , eleusive , ivan_metelsky , vexorian , rng_58

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11189

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14242&pm=11189

Problem Statement

    Teddy and Tracy are on school vacation, so they bought a puzzle book. Within the book, they discovered an interesting game called Solitaire Chess.



The game of Solitaire Chess is played on an 8 x 8 board consisting of 64 unit squares. The rows are labeled '1' through '8' from bottom to top, and the columns are labeled 'a' through 'h' from left to right. Squares are notated as "cr" (quotes for clarity), where c is the column and r is the row.



There are two kinds of pieces in Solitaire Chess: the knight, represented by the character 'N', and the pawn, represented by the character 'P'. The legal moves of each piece are shown in the diagrams below.



  abcdefgh      abcdefgh
8 ........    8 ........
7 ..X.X...    7 ........
6 .X...X..    6 ........
5 ...N....    5 ...X....
4 .X...X..    4 ...P....
3 ..X.X...    3 ........
2 ........    2 ........
1 ........    1 ........

  Knight          Pawn




In a single move, a knight can move to any one of the eight 'X' squares appearing in the left diagram, while a pawn can move to the single 'X' square appearing in the right diagram. All moves are relative to the current piece location and apply for all piece locations, provided the piece doesn't move outside the board. Moreover, a square may contain more than one piece.



If a pawn moves to the eighth row, it is immediately promoted into a knight. The promotion itself doesn't count as a move.



You are given two String[]s board1 and board2. board1 is the initial layout of the board and board2 is the desired final layout of the board. Character j of element i of board1 and board2 is 'P' if a pawn is located on the corresponding square, 'N' if a knight is located on the corresponding square, or '.' if the corresponding square is empty.



Return the minimum number of moves required to transform the initial layout into the desired layout, or -1 if it is impossible.
 

Definition

    
Class:SolitaireChess
Method:transform
Parameters:String[], String[]
Returns:int
Method signature:int transform(String[] board1, String[] board2)
(be sure your method is public)
    
 

Notes

-Elements 0 through 7 of both board1 and board2 correspond to rows '8' through '1', respectively.
-Characters 0 through 7 of each element of both board1 and board2 correspond to columns 'a' through 'h', respectively.
 

Constraints

-board1 and board2 will each contain exactly 8 elements.
-Each element of both board1 and board2 will contain exactly 8 characters.
-Each character of each element of both board1 and board2 will be one of '.', 'P', and 'N'.
-Element 0 of both board1 and board2 will not contain the character 'P'.
-board1 and board2 will each contain at most 20 pieces as described above.
 

Examples

0)
    
{"...N....",
 "........",
 "........",
 "........",
 "........",
 "........",
 "...P....",
 "........"}
{"...N....",
 ".....N..",
 "........",
 "........",
 "........",
 "........",
 "........",
 "........"}
Returns: 7
Move the pawn on d2 to d8 (6 moves), promoting it into a knight. Then move one of the knights on d8 to f7.
1)
    
{"........",
 "........",
 "...P....",
 "........",
 "........",
 "........",
 "........",
 "........"}
{"........",
 "........",
 "........",
 "........",
 "........",
 "........",
 "........",
 "...P...."}
Returns: -1
A pawn cannot move backward.
2)
    
{"........",
 "........",
 "........",
 "........",
 "........",
 "........",
 "........",
 ".N...P.."}
{"........",
 "........",
 "........",
 "........",
 "........",
 "........",
 ".....P..",
 ".......N"}
Returns: 5
One optimal solution is:
  1. Move the pawn on f1 to f2.
  2. Move the knight on b1 to c3.
  3. Move the knight on c3 to e2.
  4. Move the knight on e2 to g3.
  5. Move the knight on g3 to h1.
3)
    
{"N.......",
 "........",
 "N.......",
 "........",
 "........",
 "........",
 "........",
 "........"}
{"........",
 "..N.....",
 "........",
 "........",
 "........",
 "........",
 "........",
 "........"}
Returns: -1
4)
    
{"..N.N...",
 "PPP....N",
 "..N..N..",
 "N...N...",
 "...NNNNN",
 "N.......",
 "...NN...",
 "..N...N."}
{"..N....N",
 "P....N..",
 "..N..N..",
 "N..NNN.N",
 "N.....N.",
 "N.N.....",
 "...NNN..",
 ".....N.N"}
Returns: 23

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

YetAnotherHamiltonianPath

Graph Theory, Greedy, String Manipulation



Used in:

SRM 496

Used as:

Division I Level Three

Writer:

gojira_tc

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11147

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14425&pm=11147

Problem Statement

    A Hamiltonian path in an undirected graph with N vertices is a sequence of vertices A1, A2, ..., AN such that all Ai are pairwise distinct and for each i (1 < i &le N), there is an edge between vertices Ai-1 and Ai. A path starts at vertex A1 and visits each vertex of the sequence in order, ending at vertex AN. The cost of a path is the sum of the weights of the edges connecting the path's consecutive vertices.



You're given a graph where the i-th (0-based) vertex is labeled with String label[i]. There is an edge between each pair of vertices. The cost of the edge between vertices i and j is equal to length^2 (label[i]) + length^2 (label[j]) - length^2 (LCP (label[i], label[j]) ), where "^2" denotes squaring operation, length(X) is the length of string X and LCP(X,Y) is the longest common prefix of strings X and Y.



Return the minimum possible cost of a Hamiltonian path which starts at vertex 0 and ends at vertex 1.
 

Definition

    
Class:YetAnotherHamiltonianPath
Method:leastCost
Parameters:String[]
Returns:int
Method signature:int leastCost(String[] label)
(be sure your method is public)
    
 

Notes

-A prefix of string S is a string that can be obtained by removing zero or more contiguous characters from the end of S.
-The longest common prefix of two strings A and B is the longest possible string which is a prefix of both A and B.
 

Constraints

-label will contain between 2 and 50 elements, inclusive.
-Each element of label will be between 1 and 50 characters long, inclusive.
-Each element of label will consist of lowercase letters ('a'-'z') only.
 

Examples

0)
    
{"home", "school", "pub"} 
Returns: 70
The only possible Hamiltonian path from vertex 0 to vertex 1 is 0->2->1. Vertex 0 is labeled "home", and vertex 1 is labeled "pub", so since these two strings have no common prefix, the cost of the edge 0->1 is 4^2+3^2=25. The cost of the edge 2->1 is 45, so the total cost of the path is 70.
1)
    
{"school", "home", "pub", "stadium"}
Returns: 167
Of the two possible Hamiltonian paths, the cost of the one that visits "stadium" right after "school" is 1 less than the other one's.
2)
    
{"abcd","aecgh","abef","aecd"}
Returns: 91
The cost matrix of this graph is:

-- 40 28 31

40 -- 40 32

28 40 -- 31

31 32 31 --



The optimal path is "abcd"->"abef"->"aecd"->"aecgh".
3)
    
{"canada", "cyprus", "croatia", "colombia", "chile", "china", "cameroon"}
Returns: 509

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AfraidOfEven

Simple Math



Used in:

Member SRM 485

Used as:

Division I Level One , Division II Level Two

Writer:

ivan_metelsky

Testers:

mohamedafattah , gojira_tc , sl2

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11146

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14238&pm=11146

Problem Statement

    A sequence of integers a[0], a[1], ..., a[N-1], where N >= 3, is called an arithmetic progression if the difference between any two successive terms in the sequence is a constant. More precisely, it is an arithmetic progression if a[i] - a[i-1] = a[i+1] - a[i] for every integer i such that 0 < i < N-1.



Sasha and Pasha are students sharing the same room. Once, when Pasha had left the room, Sasha was in a good mood. So he took a piece of chalk and wrote an arithmetic progression on the blackboard. The progression consisted of at least 4 elements, all of which were positive integers. Then Sasha went to class, and Pasha came back.



Pasha is a very nice person, but there's one problem with him -- he's frightened of even numbers! So, when he returned, he decided to make all the numbers on the board odd. He did this by repeatedly finding an arbitrary even number X, erasing it, and writing X/2 in its place. He continued to perform this step until no even numbers remained.



Your task is to help Sasha restore the initial progression. You will be given a int[] seq, where the i-th element is the i-th number in the sequence written on the blackboard after Pasha's actions. Return an int[] whose i-th element is the i-th number in a sequence that Sasha could have originally written on the blackboard. The constraints will ensure that at least one such sequence exists. If there are several such sequences, choose the one among them whose int[] representation is lexicographically smallest.
 

Definition

    
Class:AfraidOfEven
Method:restoreProgression
Parameters:int[]
Returns:int[]
Method signature:int[] restoreProgression(int[] seq)
(be sure your method is public)
    
 

Notes

-The lexicographically smaller of two different int[]s containing the same number of elements is the one with a smaller number at the first position where they differ.
-It is guaranteed that all elements of the resulting int[] will fit into a 32-bit signed integer data type.
 

Constraints

-seq will contain between 4 and 50 elements, inclusive.
-Each element of seq will be between 1 and 1000, inclusive.
-Each element of seq will be odd.
-There will exist at least one arithmetic progression from which Pasha would produce exactly the sequence described by seq.
 

Examples

0)
    
{1, 1, 3, 1, 5}
Returns: {1, 2, 3, 4, 5 }
If the progression written by Pasha was {1, 2, 3, 4, 5}, then Sasha would divide 2 by 2 once and 4 by 2 twice to produce exactly {1, 1, 3, 1, 5}. Note that Pasha could have written other progressions, e.g., {2, 4, 6, 8, 10}, but {1, 2, 3, 4, 5} has the lexicographically smallest int[] representation.
1)
    
{9, 7, 5, 3, 1}
Returns: {9, 7, 5, 3, 1 }
It is possible that all terms in the original progression were odd. In this case Pasha wouldn't perform any replacements.



Note that an arithmetic progression doesn't have to be an increasing sequence.
2)
    
{999, 999, 999, 999}
Returns: {999, 999, 999, 999 }
A sequence where all terms are the same is also an arithmetic progression.
3)
    
{7, 47, 5, 113, 73, 179, 53}
Returns: {14, 47, 80, 113, 146, 179, 212 }
4)
    
{749, 999, 125, 1}
Returns: {1498, 999, 500, 1 }
Some elements of the original progression could be greater than 1000.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CubeColoring

Brute Force, Graph Theory



Used in:

SRM 484

Used as:

Division II Level Three

Writer:

rng_58

Testers:

PabloGilberto , ivan_metelsky , pieguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11130

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14237&pm=11130

Problem Statement

    NOTE: This problem statement contains images that may not display properly if viewed outside of the applet.



Rabbit Taro wants to color the vertices of a cube. He thinks the cube will be beautiful if:
  • Each vertex is colored by a color that is suitable for it.
  • No two adjacent vertices have the same color.




There are N types of colors. You are given a String[] colors. The j-th color is suitable for the i-th vertex if the j-th character of the i-th element of colors is 'Y'. Return the number of different ways to color the cube.
 

Definition

    
Class:CubeColoring
Method:theCount
Parameters:String[]
Returns:long
Method signature:long theCount(String[] colors)
(be sure your method is public)
    
 

Notes

-Two ways are different if there exists an i such that the i-th vertex has a different color in one way than it does in the other way.
 

Constraints

-colors will contain exactly 8 elements.
-Each element in colors will contain between 1 and 32 characters, inclusive.
-Each element in colors will contain the same number of characters.
-Each character in colors will be 'Y' or 'N'.
 

Examples

0)
    
{"Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y"}
Returns: 0
It's impossible to color the cube by only 1 color.
1)
    
{"YNNNNNNN", "NYNNNNNN", "NNYNNNNN", "NNNYNNNN", "NNNNYNNN", "NNNNNYNN", "NNNNNNYN", "NNNNNNNY"}
Returns: 1
Color the i-th vertex by the i-th color.
2)
    
{"YNNYN", "YYYYY", "NYYNY", "YNYYN", "YNNYY", "YNNYY", "NNNYY", "NYYYY"}
Returns: 250
3)
    
{"YNNYN", "YYYYY", "NNNNN", "YNYYN", "YNNYY", "YNNYY", "NNNYY", "NYYYY"}
Returns: 0
No color is suitable for vertex 2.
4)
    
{"YNNYNYYYYYNN", "NNNYNYYNYNNY", "YYNNYYNNNYYN", "YYYYYNNYYYNN", "NNNYYYNNYNYN", "YYYNYYYYNYNN", "NNNNNNYYNYYN", "NNYNYYNNYNYY"}
Returns: 611480

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TimeTravellingGogo

Graph Theory



Used in:

SRM 492

Used as:

Division I Level Three

Writer:

dolphinigle

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11117

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14245&pm=11117

Problem Statement

    Gogo lives in Rainyland and wants to attend a party. There are N houses in Rainyland, conveniently numbered 0 through N-1. Gogo lives in house 0 and the party is in house N-1. There are several bidirectional roads of various lengths that Gogo can traverse.



It rains a lot in Rainyland. In fact, with the exception of several sunny intervals, it rains all the time. The i-th sunny interval starts at the beginning of minute sunnyStart[i] and ends at the beginning of minute sunnyEnd[i]. Gogo can't get his party clothes wet, so whenever it is raining, he must be inside a house. He can only traverse roads during sunny intervals. More exactly, if he starts traversing a road at the beginning of minute A and ends at the beginning of minute B, there must exist such i that sunnyStart[i] <= A < B <= sunnyEnd[i].



The roads are given in the String[] roads. Concatenate the elements of roads to get a single space separated list of roads. Each road is formatted "a,b,travelcost" (quotes for clarity), which means that the bidirectional road connects city a and city b, and requires travelcost minutes to traverse either way.



Gogo also has a time machine, which he can use to go back in time. He can only use the time machine inside a house, and it requires machineStartTime + X minutes to go back in time by X minutes. He can go back as far as time 0, but no further. For example, suppose the time is currently 100, machineStartTime is 10, and he wants to go back to time 80 because it was sunny then. It will take him 10 + 20 = 30 minutes to get back to time 80. Note that when he uses the time machine, his position will not change. In other words, he won't go back to where he happened to be at time 80 the last time he was there.



Gogo is initially in his house at the beginning of minute 0. Return the minimum number of minutes Gogo needs to reach house N-1 without getting wet. Return -1 if it's impossible. Note that Gogo does not have to be in constant motion. For example, he can wait inside a house while waiting for a sunny interval. Also, note that time travel does not affect Gogo's total time. For example, in the scenario described above, if he used the time machine for the first time at time 100, then when he goes back to time 80, his total time will be 130 minutes, not 80 minutes.
 

Definition

    
Class:TimeTravellingGogo
Method:determineTime
Parameters:int, int[], int[], String[], int
Returns:long
Method signature:long determineTime(int N, int[] sunnyStart, int[] sunnyEnd, String[] roads, int machineStartTime)
(be sure your method is public)
    
 

Constraints

-N will be between 2 and 20, inclusive.
-sunnyStart will contain between 1 and 20 elements, inclusive.
-Each element of sunnyStart will be between 0 and 999,999,999, inclusive.
-sunnyEnd will contain the same number of elements as sunnyStart.
-sunnyEnd[i] will be between sunnyStart[i]+1 and 1,000,000,000, inclusive.
-There will be at least a minute of rain between two sunny intervals, that is, sunnyEnd[i] < sunnyStart[i+1].
-roads will contain between 1 and 50 elements, inclusive.
-Each element of roads will contain between 1 and 50 characters, inclusive.
-Each character in roads will be '0'-'9', ' ', or ','.
-roads will be formatted as described in the problem statement without leading or trailing spaces.
-All integers in the concatenation of all the elements of roads in the order they are given will have no extra leading zeroes.
-In each road, a and b as described in the problem statement will be different and will each be between 0 and N-1, inclusive.
-In each road, travelcost as described in the problem statement will be between 1 and 1,000,000,000, inclusive.
-For each two different houses, there will be at most one road connecting them.
-machineStartTime will be between 1 and 1,000,000,000, inclusive.
 

Examples

0)
    
3
{0,8}
{4,12}
{"0,1,3 1,2,3"}
1
Returns: 9
First, walk from house 0 to house 1, arriving at minute 3. Then, go back in time to minute 1. This time travel requires 1+2=3 minutes. Finally, walk 3 minutes from house 1 to house 2, arriving at minute 4. The total time is 3+3+3=9 minutes.
1)
    
3
{0,8}
{4,12}
{"0,1,3 1,2,4"}
18
Returns: 12
First, walk from house 0 to house 1, arriving at minute 3. Then, wait inside house 1 for 5 minutes. Finally, walk 4 minutes from house 1 to house 2, arriving at minute 12. The total time is 3+5+4=12 minutes.
2)
    
2
{1,3}
{2,4}
{"0,1,2"}
1
Returns: -1
The length of each sunny interval is 1 minute, but the road from house 0 to house 1 requires 2 minutes to traverse, so it is impossible for Gogo to arrive at the party without getting his clothes wet.
3)
    
3
{0,17}
{15,37}
{"0,1,1","5"," 1,2,12 2,0,17"}
10
Returns: 29

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PermutationSignature

Greedy, Simple Math



Used in:

SRM 497

Used as:

Division I Level One , Division II Level Two

Writer:

misof

Testers:

SnapDragon , Rustyoldman , marek.cygan , timmac , ivan_metelsky , Egor , Chmel_Tolstiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11115

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14426&pm=11115

Problem Statement

    

The signature of a permutation is a string that is computed as follows: for each pair of consecutive elements of the permutation, write down the letter 'I' (increasing) if the second element is greater than the first one, otherwise write down the letter 'D' (decreasing).

For example, the signature of the permutation {3,1,2,7,4,6,5} is "DIIDID".

Your task is to reverse this computation: You are given a String signature containing the signature of a permutation. Find and return the lexicographically smallest permutation with the given signature. If no such permutation exists, return an empty int[] instead.

 

Definition

    
Class:PermutationSignature
Method:reconstruct
Parameters:String
Returns:int[]
Method signature:int[] reconstruct(String signature)
(be sure your method is public)
    
 

Notes

-For any positive integer N, a permutation of N elements is a sequence of length N that contains each of the integers 1 through N exactly once.
-To compare two permutations A and B, find the smallest index i such that A[i] and B[i] differ. If A[i] < B[i], we say that A is lexicographically smaller than B, and vice versa.
 

Constraints

-signature will contain between 1 and 50 characters, inclusive.
-Each character in signature will be either 'I' or 'D'.
 

Examples

0)
    
"IIIII"
Returns: {1, 2, 3, 4, 5, 6 }
1)
    
"DI"
Returns: {2, 1, 3 }
There are two permutations with this signature: {3,1,2} and {2,1,3}. You must return the lexicographically smaller one.
2)
    
"IIIID"
Returns: {1, 2, 3, 4, 6, 5 }
3)
    
"DIIDID"
Returns: {2, 1, 3, 5, 4, 7, 6 }
This is the signature from the problem statement. Note that the correct answer is not the permutation from the problem statement.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TicketPrinters

Brute Force, Graph Theory, Search



Used in:

SRM 481

Used as:

Division I Level Three

Writer:

vexorian

Testers:

PabloGilberto , ivan_metelsky , Chmel_Tolstiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11107

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14234&pm=11107

Problem Statement

    After 2 years of hard work, it is finally time to unveil the ultimate plan to win the lottery. This plan involves mostly cartomancy, falsification and programming. The tarot specialist has already predicted the N numbers of the required lottery tickets, and they are given as a int[] wantedValues. The falsification specialist has prepared a set of N ticket printers and he has taken a number of security measures to make it very hard to discover the scheme:



  • The printers are in separate locations. For convenience, they are all hidden inside houses that are all on a single street. The distances between each consecutive pair of printers are given by int[] printerDistance, which contains (n-1) elements. For each i, the time required to travel between printer i and printer i+1 is printerDistance[i] seconds.
  • The way a printer functions is by keeping a hidden integer number in its memory. For security, increasing or decreasing the number by one requires 1 second. At any time, it is possible to order the printer to print the number it has in memory. This procedure also takes 1 second. The starting number for printer i is startingValues[i]
  • Each printer can print at most one ticket.
Your role as the programmer is to go to each printer and print the required lottery tickets given by wantedValues. You are currently in the same location as printer number currentPrinter. Since you do not understand why they even hired a programmer for the scheme, you have decided to use programs to save time in this process. The first program you have developed can, given a wanted number, modify the one in the printer by automatically increasing or decreasing it and finally print the wanted number automatically (increasing/decreasing the numbers and printing them still requires one second). You can install this program to each printer once you are its location. The installation doesn't take any time. Once the program is installed, it can work without any administration from your side, so you can immediately proceed to the next printer.



Now your task is to develop the second program that should determine in which order to visit printers and which printer to use for printing of each of the tickets. Return the outcome of the second program, i.e., the minimum time that is necessary to finish printing all the required numbers.
 

Definition

    
Class:TicketPrinters
Method:minTime
Parameters:int, int[], int[], int[]
Returns:int
Method signature:int minTime(int currentPrinter, int[] printerDistance, int[] startingValues, int[] wantedValues)
(be sure your method is public)
    
 

Constraints

-wantedValues will contain between 1 and 16 elements, inclusive.
-startingValues will contain n elements, where n is the number of elements in wantedValues.
-printerDistance will contain exactly n-1 elements.
-currentPrinter will be between 0 and n-1, inclusive.
-Each element of startingValues, printerDistance and wantedValues will be between 1 and 1000000, inclusive.
-Each element of wantedValues will be unique.
 

Examples

0)
    
0
{100, 20, 50}
{66, 78, 99, 5}
{99, 5, 78, 66}
Returns: 171
1)
    
1
{50, 50}
{100, 200, 300}
{101, 201, 302}
Returns: 152
A possible way to print the tickets is:



0 seconds: Start printing program up at printer 1 to print ticket #201. Begin moving to printer 2's position.

1 second: Printer 1 reaches number 201 in memory.

2 seconds: Printer 1 finishes printing its assigned ticket.

50 seconds: Arrive at printer 2's location. Order it to print ticket #302. Begin moving to printer 0's position.

52 seconds: Printer 2 reaches number 302 in memory.

53 seconds: Printer 2 finishes printing its assigned ticket.

150 seconds: Arrive at printer 0's location. Order it to print ticket #101.

151 seconds: Printer #0 reaches number #101 in memory.

152 seconds: Printer #0 finishes printing ticket #101.
2)
    
2
{13, 26, 39, 13}
{123, 12, 32, 67, 1015}
{1, 2, 3, 4, 5}
Returns: 1063

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TimeTravellingSalesman

Graph Theory



Used in:

SRM 492

Used as:

Division II Level Three

Writer:

dolphinigle

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11049

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14245&pm=11049

Problem Statement

    A traveling salesman wants to survey N cities for business opportunities. The cities are numbered 0 through N-1, and he wishes to visit each of them at least once. He starts at city 0 and can end at any city. There are several bidirectional roads, each connecting two different cities and costing some amount of money to traverse.



The traveling salesman also has a time machine. He can use the time machine to go back in time, without affecting which cities he is considered to have already visited. For example, suppose he has visited cities A, B, C, D, and E, in that order, and is currently in city E. He can use the time machine to go back to city A, B, C, or D. Suppose he chooses to go back to city C. At that point, he can then go back further to city A or B, but he cannot use the time machine to go forward to city D or E. Note that going back in time will not change the fact that he is considered to have already visited cities A, B, C, D, and E.



You are given the roads in the String[] roads. Concatenate the elements of roads, in order, to get a single space-separated list of roads. Each road will be formatted "a,b,travelcost" (quotes for clarity), which means that the bidirectional road connects city a and city b, and costs travelcost to traverse.



He can use the time machine any number of times, and it costs nothing to use it. Return the minimum cost required to visit all the cities. Return -1 if it is impossible to visit all the cities.
 

Definition

    
Class:TimeTravellingSalesman
Method:determineCost
Parameters:int, String[]
Returns:long
Method signature:long determineCost(int N, String[] roads)
(be sure your method is public)
    
 

Constraints

-N will be between 2 and 1000, inclusive.
-roads will contain between 1 and 50 elements, inclusive.
-Each element of roads will contain between 1 and 50 characters, inclusive.
-Each character in roads will be '0'-'9', ',' or ' '.
-roads will be formatted as described in the problem statement without leading or trailing spaces.
-All integers in the concatenation of all the elements of roads in the order they are given will have no extra leading zeroes.
-In each road, a and b as described in the problem statement will be different and will each be between 0 and N-1, inclusive.
-In each road, travelcost as described in the problem statement will be between 1 and 10,000,000, inclusive.
-For each two different cities, there will be at most one road connecting them.
 

Examples

0)
    
3
{"0,1,1 0,2,1 1,2,2"}
Returns: 2
Travel from city 0 to city 1. Go back in time to city 0. Travel from city 0 to city 2. The total cost is 1+1=2.
1)
    
6
{"0,1,2 1,4,2 4,3,3 2,4,4 0,5,3"}
Returns: 14
Travel from city 0 to city 1 to city 4 to city 3. Go back in time to city 4. Travel from city 4 to city 2. Go back in time to city 0. Travel from city 0 to city 5. The total cost is 2+2+3+4+3=14.
2)
    
3
{"0,2,2"}
Returns: -1
It is impossible to reach city 1.
3)
    
4
{"1,0",",10","0 2,1",",584 3,2",",754"}
Returns: 1438

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheAirTripDivTwo

Graph Theory, Simple Search, Iteration



Used in:

SRM 479

Used as:

Division II Level One

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , ivan_metelsky , gojira_tc

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11031

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14158&pm=11031

Problem Statement

    John and Brus have their own airplane. They are going to take several consecutive flights. The i-th element of flights is the number of liters of fuel needed for the i-th flight. The flights can be performed only in the same order as they are described in flights.



Initially there are fuel liters of fuel in the airplane. In order to perform a flight, the amount of fuel in the airplane must be at least as much as the amount of fuel needed for this flight. Return the maximum number of flights they will be able to make without a refuel.
 

Definition

    
Class:TheAirTripDivTwo
Method:find
Parameters:int[], int
Returns:int
Method signature:int find(int[] flights, int fuel)
(be sure your method is public)
    
 

Constraints

-flights will contain between 1 and 47 elements, inclusive.
-Each element of flights will be between 1 and 1000, inclusive.
-fuel will be between 1 and 1000, inclusive.
 

Examples

0)
    
{1, 2, 3, 4, 5, 6, 7}
10
Returns: 4
Exactly 10 liters of fuel are required to perform the first four flights.
1)
    
{7, 6, 5, 4, 3, 2, 1}
10
Returns: 1
These are the same flights as in the previous example, but in different order.
2)
    
{1}
1000
Returns: 1
A single flight here.
3)
    
{8, 7, 7, 1, 5, 7, 9}
21
Returns: 2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheAirTripDivOne

Graph Theory, Simple Math



Used in:

SRM 479

Used as:

Division I Level Two

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , ivan_metelsky , gojira_tc

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11030

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14158&pm=11030

Problem Statement

    In some country there are n cities numbered from 1 to n. There are also several types of flights between them. Each flight type is characterized with 5 integers A, B, F, T and P. All flights of this type depart from city A and arrive at city B (without changing planes in any intermediate cities). Each flight type is one-directional, so it is impossible to fly from city B to city A using the same flight type. All flights of the same type depart with some periodicity. More precisely, the first flight of this type departs from A at time F, the next flight departs at time F + P, then at F + 2P, and so on (there are infinitely many flights of the same type). Each flight of the same type has the same flight time T. I.e., if a plane departs from A at time T0, then it arrives to B at time T0 + T.



The description of all flight types is given in String[] flights. Concatenate the elements of this String[] in the same order as they are given without any delimiters between its elements to get a single String. This String will contain a single space separated list of flight type descriptions. Each such description will be of the form "A,B,F,T,P" (quotes for clarity), where the meaning of integers A, B, F, T and P is exactly the same as defined in the previous paragraph.



John would like to travel from city 1 to city n where his friend Brus is waiting for him. Unfortunately, there are no direct flights from 1 to n, so he will have to use several flights to reach city n. He can't use any other transport besides planes, so the departure city of each next flight he takes must be the same as the arrival city of the previous flight he has taken. Moreover, in order for him to be able to change planes, the departure time of each next flight must be strictly greater than the arrival time of the previous flight. If he arrives at some city at time T1 and then departs at time T2, the waiting time in this city is equal to T2 - T1. John defines the safety of his route from 1 to n as the minimum of waiting times over all cities where he changes flights.



John wants to arrive at city n no later than at time moment time. If there are several routes that achieve this goal, he wants to choose the route among them with the maximum possible safety. Return this maximum possible safety. If there are no such routes, return -1.
 

Definition

    
Class:TheAirTripDivOne
Method:find
Parameters:int, String[], int
Returns:int
Method signature:int find(int n, String[] flights, int time)
(be sure your method is public)
    
 

Constraints

-n will be between 3 and 477, inclusive.
-flights will contain between 1 and 47 elements, inclusive.
-Each element of flights will contain between 1 and 47 characters, inclusive.
-The concatenation of all elements of flights will be a single space separated list of flight type descriptions without leading or trailing spaces.
-Each flight type description will be of form "A,B,F,T,P" (quotes for clarity), where A, B, F, T and P are integers formatted with no extra leading zeros.
-In each flight type, A and B will be distinct integers between 1 and n, inclusive.
-In each flight type, F, T and P will be between 1 and 1,000,000,000, inclusive.
-There will be no flight from city 1 to city n.
-time will be between 1 and 1,000,000,000, inclusive.
 

Examples

0)
    
3
{"1,2,1,4,7 ", "2,3,9,1,10"}
20
Returns: 14
The optimal way is to take the first flight at time 1 and the second one at time 19.
1)
    
3
{"1,2,1,1,1 2,3,2,1,98"}
100
Returns: -1
Since John needs a strictly positive time to change a flight, it is possible to get to city 3 only at time 101.
2)
    
477
{"47,74,1,1,1"}
20
Returns: -1
It is impossible to reach the destination at all.
3)
    
7
{"1,3,15,17,11 1,3,14,16,14 5,7,12,18,18 1,6,13,1", 
 "6,12 1,2,18,14,13 5,6,10,10,18 3,1,10,10,10 1,3",
 ",17,16,10 2,3,16,18,16 6,1,15,12,10 2,1,15,18,1",
 "0 4,7,10,16,15 6,3,10,14,10 1,6,19,19,15 1,4,12",
 ",10,14 4,7,10,18,14 2,3,16,12,12 1,3,14,10,19 3",
 ",7,17,10,12 2,1,14,12,16 4,3,19,11,12 1,6,10,18",
 ",12 2,3,16,12,10 6,2,10,18,12 5,1,14,18,12 5,1,",
 "18,10,10 3,2,19,15,10 7,4,16,19,14 6,3,16,12,10",
 " 5,7,14,13,13 1,3,12,10,16 5,7,16,18,15 6,2,18,",
 "12,14 3,2,10,18,16 4,2,18,18,14 1,5,10,18,16 2,",
 "3,10,19,16 1,4,11,18,15 2,1,15,15,14 7,2,10,12,",
 "10"}
74
Returns: 33
Note that there can be multiple flight types with the same departure city and the same arrival city.
4)
    
7
{"1,4,10,8,2 4,6,14,8,2 6,2,8,1",
 "0,1 2,7,19,5,1 ",
 "1,5,15,17,11 5,3,10,1",
 "0,18 3,7,12,18,18"}
147
Returns: 35
Take the flight from city 1 to city 4 at time 10 to arrive at city 4 at time 18. Then take the flight from city 4 to city 6 at time 54 to arrive at city 6 at time 62. Next take the flight from city 6 to city 2 at time 97 to arrive at city 2 at time 107. Finally, take the flight from city 2 to city 7 at time 142 to arrive at city 7 exactly at time 147. The safety of this route is min{54 - 18, 107 - 62, 142 - 107} = 35.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SubgraphIsomorphism

Graph Theory



Used in:

TCO10 Round 3

Used as:

Division I Level One

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11016

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14274&pm=11016

Problem Statement

    In this problem you will be given a large graph formed by a random process. You will then be asked to find a series of subgraphs of ever-increasing size. Your task is to answer as many queries as possible before time runs out.



An undirected graph G = (V,E) is defined by a set of vertices, V, indexed from 0 to N-1 and a set of edges (u,v). As the graph is undirected, each edge will be listed in both directions. An induced subgraph H of G is defined by a subset of vertices V' and all of the edges in E where both u and v are in V'. See Wikipedia for a more rigorous definition.



In the induced subgraph isomorphism problem, you are given two graphs: a graph G with N vertices, and a graph H with K vertices. Your task is to find a mapping f() from 0..K-1 to 0..N-1 such that (u,v) is an edge in H if and only if (f(u), f(v)) is an edge in G. Again, see Wikipedia for a formal definition.



In this problem, you will be given a graph G, followed by a series of smaller graphs H5, H6, H7, ... (starting from H5 intentionally). Hi will be an induced subgraph of G on i vertices. For each such query, you should return a int[] with i elements, where element j of your return represents f(j) above.



Each graph input will be formatted as a single int[]. The first element of the array will give the number of vertices. The degrees of the nodes will then be listed one at a time, along the their lists of neighbors. Thus, the following pseudocode will decode the input:
	ptr = 0
	vertices = input[ptr++]
	for (i = 0; i < vertices; i++) 
		degree = input[ptr++]
		for (j = 0; j < degree; j++) 
			createEdge(i, input[ptr++])
where createEdge(u,v) creates an edge in whatever data structure you choose to use.



Scoring

You will be given 10 seconds of total execution time. A function initialize will take the large graph G, and should return an integer (it doesn't matter what you return here). A function query will then be called repeatedly, starting with H5. Your 10 seconds includes the time spent in these functions (both initialize and query). Your query function will be called until you either run out of time, or give an incorrect return (one that isn't a match, or isn't valid). Your score for each test case will simply be the number of queries answered correctly before time runs out (or an incorrect return). Your overall score for all test cases will be the sum of your scores on all the individual test cases.

Test Generation

The graph G will be generated by first picking three values: N, alpha, and D. N will be chosen uniformly at random in [1000,20000]. Alpha will be a floating point number uniformly at random in [1,3). D will be an integer chosen uniformly in [2,30].



For vertex i, a location (xi,yi) will be chosen with xi and yi each integers in [0,220). For each vertex i, we will then generate D undirected edges (i,j). Given a choice of i, each j will be chosen with probability proportional to (1+dist(i,j))-alpha, where dist(i,j) = sqrt((xi-xj)2 + (yi-yj)2). The choices of j will be made with replacement, so the same j may be chosen multiple times. After all selection are made, duplicates are eliminated, leaving a simple undirected graph.



To select each Hi, a seed vertex u will be chosen uniformly at random from the N vertices in G. All neighbors of u will be added to the set of frontier vertices. Then, a node is chosen randomly from the set of frontier vertices and all of its neighbors are added to the frontier. A node added to the frontier multiple times will have multiple chances to be selected (making the frontier a multiset). This process is repeated until i vertices are chosen. If the frontier set becomes empty before i vertices have been selected, the select process is restarted from scratch. Finally, the subgraph is extracted and the vertex labels are randomly shuffled.

Offline Tool

An offline testing tool is provided here.
 

Definition

    
Class:SubgraphIsomorphism
Method:initialize
Parameters:int[]
Returns:int
Method signature:int initialize(int[] G)
 
Method:query
Parameters:int[]
Returns:int[]
Method signature:int[] query(int[] H)
(be sure your methods are public)
    
 

Notes

-The time limit is 10 seconds.
-The memory limit is 1024MB.
-Your method will be queried until you run out of time, or until the size of the subgraph is equal to the largest connected component in G.
-There are 50 test cases.
 

Examples

0)
    
"1"
Returns: "seed = 1<br>
N = 13878<br>
alpha = 2.178079240820598<br>
deg = 9<br>
"
1)
    
"2"
Returns: "seed = 2<br>
N = 19425<br>
alpha = 1.8807096080672547<br>
deg = 16<br>
"
2)
    
"3"
Returns: "seed = 3<br>
N = 7403<br>
alpha = 2.6339482751431706<br>
deg = 21<br>
"
3)
    
"4"
Returns: "seed = 4<br>
N = 11809<br>
alpha = 2.743153197688343<br>
deg = 4<br>
"
4)
    
"5"
Returns: "seed = 5<br>
N = 15638<br>
alpha = 1.8666642015582442<br>
deg = 7<br>
"
5)
    
"6"
Returns: "seed = 6<br>
N = 13268<br>
alpha = 2.9672762511627835<br>
deg = 30<br>
"
6)
    
"7"
Returns: "seed = 7<br>
N = 6674<br>
alpha = 1.726463701449059<br>
deg = 8<br>
"
7)
    
"8"
Returns: "seed = 8<br>
N = 18559<br>
alpha = 1.8207492412680386<br>
deg = 27<br>
"
8)
    
"9"
Returns: "seed = 9<br>
N = 2650<br>
alpha = 2.3528908831563458<br>
deg = 12<br>
"
9)
    
"10"
Returns: "seed = 10<br>
N = 2706<br>
alpha = 1.545583100723283<br>
deg = 5<br>
"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BunnyExam

Brute Force, Graph Theory, Simple Math



Used in:

SRM 487

Used as:

Division I Level Two

Writer:

lyrically

Testers:

PabloGilberto , ivan_metelsky , soul-net

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11011

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14240&pm=11011

Problem Statement

    Bunnies like programming and they sometimes make useful devices.



One group of bunnies made a device called RandomAnswerer for their final exam. They cannot solve any of the problems, so they will try to answer the questions randomly.



There are m problems numbered 1 through m. The answer for each problem will be one of the integers between 1 and k, inclusive. We also know the following:
  • The answer to problem x is different from that of problem x + 1, where 1 <= x < m.
  • We have a int[] linkage containing N * 2 elements. For each i, where 0 <= i < N, the answer to problem linkage[i * 2] is the same as that of linkage[i * 2 + 1]. Note that all elements in linkage are distinct.
RandomAnswerer makes a sequence of m answers and shows it to the bunnies. Both the sequence produced by RandomAnswerer and the sequence of correct answers are chosen among all possible sequences of m answers that agree with the information above, randomly (all of them have the same probability of being chosen) and independently. Return the expected number of correct answers bunnies get. If there is any contradiction in the information, i.e., there are no sequences of answers that agree with all of it, return -1.0 instead.
 

Definition

    
Class:BunnyExam
Method:getExpected
Parameters:int, int, int[]
Returns:double
Method signature:double getExpected(int m, int k, int[] linkage)
(be sure your method is public)
    
 

Notes

-The returned value must have an absolute or relative error less than 1e-9.
 

Constraints

-m and k will each be between 1 and 1,000,000,000, inclusive.
-linkage will contain between 0 and 20 elements, inclusive.
-linkage will contain an even number of elements.
-Each element of linkage will be between 1 and m, inclusive.
-All elements of linkage will be distinct.
 

Examples

0)
    
3
2
{ 1, 3 }
Returns: 1.5
Here problems 1 and 2 have different answers, problems 2 and 3 have different answers and problems 1 and 3 have the same answer.

The answers will be either (1, 2, 1) or (2, 1, 2), so the number of correct answers bunnies get will be 3 or 0 with equal probability.
1)
    
4
2
{ 1, 4 }
Returns: -1.0
This is impossible.
2)
    
2
8
{ }
Returns: 0.25
linkage may be empty.
3)
    
1000000000
1
{ 11, 13, 2010, 487 }
Returns: -1.0
4)
    
128
64
{ 32, 16, 8, 4, 2, 1 }
Returns: -1.0
5)
    
13
3
{ 1, 3, 7, 9, 13, 10, 6, 2  }
Returns: 4.333333333333333

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

KingdomTour

Dynamic Programming, Graph Theory



Used in:

SRM 477

Used as:

Division I Level Three

Writer:

keshav_57

Testers:

PabloGilberto , ivan_metelsky , mohamedafattah

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=11003

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14157&pm=11003

Problem Statement

    The king loves his queen a lot, and he wants to take her all over the kingdom, in just a single day.



The kingdom has N cities in it. There are bi-directional roads connecting the cities such that there is a unique path from any city in the kingdom to any other city. Each road has an integral length.



The king wants to take his queen on a tour in the kingdom which starts and ends at the kingdom's capital. Since the kingdom is really beautiful, the king wants the tour to cover each road in the kingdom at least once (it doesn't matter in which direction). However, he has been informed that this might take a really long time. Hence, he has decided to build at most K shortcuts. A shortcut can connect any two cities (even if they are directly connected by a road), and the length of a shortcut is L. Since the scenery around the newly constructed shortcuts might not be so beautiful, the king has demanded that any particular shortcut cannot be taken more than once during the tour.



The cities in the kingdom are numbered 0 to N-1. City 0 is always the capital. The roads of the kingdom are described in String[] roads. Concatenate the elements of roads to get a single String. This String is a comma separated list of the roads in the kingdom in the form "A B C" (quotes for clarity), meaning that there is a road of length C connecting city A and city B.



Return the length of the shortest tour satisfying the king's demands.

 

Definition

    
Class:KingdomTour
Method:minTime
Parameters:int, String[], int, int
Returns:int
Method signature:int minTime(int N, String[] roads, int K, int L)
(be sure your method is public)
    
 

Constraints

-N will be between 2 and 200, inclusive.
-K will be between 0 and 100, inclusive.
-roads will contain between 1 and 50 elements, inclusive.
-Each element of roads will contain between 1 and 50 characters, inclusive.
-roads, when concatenated, will be a comma-separated list of roads, where each road is formatted "A B C" (quotes for clarity).
-In each road "A B C", A and B will be distinct integers between 0 and N-1, inclusive, with no extra leading zeroes, and C will be an integer between 1 and 10000, inclusive, with no leading zeroes.
-The roads will be such that the kingdom will satisfy the properties mentioned in the problem statement.
-L will be between 1 and 10000, inclusive.
 

Examples

0)
    
3
{"2 1 9,0 1 3"}
8
4
Returns: 16
If a shortcut is constructed from city 0 to city 2, then the tour 0-->1-->2-->0 has a length of 16 units.
1)
    
2
{"0 1 4"}
2
3
Returns: 7
Construct a shortcut between the only two existing cities. Traverse the road once, and use the shortcut once.
2)
    
6
{"4 0 4,2 0 4,2 5 4,4 3 1",
 "0,1 2 10"}
2
5
Returns: 41
Make sure you concatenate the elements of roads[].
3)
    
10
{"1 2 2,4 1 9,2 5 5,6 5 4,", "1 7 7,7 3 1,2 0 2", ",5 8 5,9 5 6"}
2
4
Returns: 59

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SpaceshipEvacuation

Dynamic Programming, Graph Theory



Used in:

SRM 476

Used as:

Division I Level Three

Writer:

gojira_tc

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10993

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14186&pm=10993

Problem Statement

    Manao is an engineer of a new spaceship. He is responsible for crew safety, particularly during a possible evacuation. The spaceship consists of N units numbered from 0 to N-1. The units are connected by passages, but during evacuation, moving through them is too slow and therefore is prohibited. Some pairs of units are connected by tunnels which contain emergency cabins. There are several emergency cabins at each end of each tunnel. A cabin is designed for a single person and may only be used once for security reasons. A cabin at one end of a tunnel can only be used to reach the other end of that same tunnel.



The tunnel network has a special layout. Consider a sequence of units U0, U1, ..., UK with K &ge 3 and U0=UK. If all U0, U1, ..., UK-1 are pairwise distinct and for each i, 0 &le i < K, Ui and Ui+1 are connected by a tunnel, this sequence is called a cycle. A cycle is called canonical if U0 < Ui for 1 &le i < K and U1 < UK-1. Each unit in the spaceship will be a part of at most one canonical cycle. The tunnel network is given as String[] tunnelNetwork, where each element describes a tunnel and contains four space-separated integers A, B, C, D. This means that there is a tunnel between units A and B and there are C emergency cabins in the tunnel from unit A's side and D emergency cabins from unit B's side.



The crew of the spaceship consists of crewSize members. Each of them might be in any of the N units when the evacuation is announced. Unit 0 is connected to the rescue boat, so every person reaching this unit is considered evacuated. The distribution of emergency cabins within the tunnels is called an evacuation plan. An evacuation plan is called acceptable if there exists a way to evacuate the whole crew for any possible distribution of crew members over the units at the moment when the evacuation is announced. The current evacuation plan might not be acceptable. Manao may demand a number of additional emergency cabins at each end of each tunnel, but he is not allowed to change the location of emergency cabins that are already present in the spaceship. Return the minimum total number of emergency cabins Manao has to add to obtain an acceptable evacuation plan from the current one. If it is impossible, return -1.
 

Definition

    
Class:SpaceshipEvacuation
Method:additionalCabins
Parameters:int, String[], int
Returns:int
Method signature:int additionalCabins(int N, String[] tunnelNetwork, int crewSize)
(be sure your method is public)
    
 

Constraints

-N will be between 2 and 50, inclusive.
-tunnelNetwork will contain between 1 and 50 elements, inclusive.
-Each element of tunnelNetwork will contain between 7 and 50 characters, inclusive.
-Each element of tunnelNetwork will be formatted "A B C D" (quotes for clarity), where A, B, C and D are integers formatted without extra leading zeros.
-In each element of tunnelNetwork, A and B will be distinct integers between 0 and N-1, inclusive.
-In each element of tunnelNetwork, C and D will each be between 0 and 100,000, inclusive.
-The unordered pairs {A,B} in tunnelNetwork will be distinct.
-Each unit will be a part of at most one canonical cycle.
-crewSize will be between 1 and 100,000, inclusive.
 

Examples

0)
    
3
{"0 1 5 3",
 "2 1 0 0"}
5
Returns: 7
Adding 2 cabins to the tunnel between units 0 and 1 from unit 1's side and 5 cabins to the tunnel between units 2 and 1 from unit 2's side ensures that wherever the crew members happen to be when evacuation begins, they will be able to reach unit 0.
1)
    
3
{"0 1 0 2",
 "0 2 0 4"}
5
Returns: 4
An optimal evacuation scheme can be obtained by adding 3 emergency cabins to the 0-1 tunnel and 1 emergency cabin to the 0-2 tunnel.
2)
    
4
{"0 1 0 6",
 "3 2 3 1",
 "2 1 0 1",
 "3 1 2 2"}
6
Returns: 6
One of the possible ways to obtain an optimal evacuation scheme is to add 5 cabins to the 1-2 tunnel from unit 2's side and 1 cabin to the 2-3 tunnel from unit 3's side.
3)
    
10
{"0 1 11 101",
 "1 2 0 100",
 "2 3 20 100",
 "3 4 0 107",
 "4 1 66 0",
 "3 5 104 2",
 "4 6 82 0",
 "5 7 25 25",
 "7 8 14 42",
 "8 9 0 94",
 "9 5 17 92"}
110
Returns: 376
4)
    
3
{"0 1 0 0"}
1
Returns: -1
The only crew member has no chance if he is in unit 2 at the moment of evacuation.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

OneRegister

Greedy, Simple Math



Used in:

SRM 486

Used as:

Division I Level One , Division II Level Two

Writer:

soul-net

Testers:

PabloGilberto , battyone , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10992

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14239&pm=10992

Problem Statement

    

You've designed a computer and implemented all the common arithmetic operators: addition, subtraction, multiplication and integer division. However, your budget was very limited, so you could only afford to place a single register in the computer. The register can store any non-negative integer value. Since there is only one register, there is no need to identify the store location or the operands of each operation or its result. The programming language has four instructions: '+', '-', '*' and '/'. Each instruction performs the corresponding operation using the value in the register as both its parameters. It then stores the result in the same register, overwriting the previous content.

A program for your computer is a sequential list of zero or more instructions. You want to show that, even with its limitations, your newly constructed computer is powerful. You will be given two ints s and t. Return the shortest program that finishes with a value of t in the register if it contained s before executing. If there is more than one possible answer, return the one that comes earliest lexicographically. If there is no program that can do the job, return ":-(" (quotes for clarity) instead.

 

Definition

    
Class:OneRegister
Method:getProgram
Parameters:int, int
Returns:String
Method signature:String getProgram(int s, int t)
(be sure your method is public)
    
 

Notes

-A string comes lexicographically earlier than another one of the same length if and only if it contains a symbol with a lower ASCII code in the first position at which they differ. The operators in ascending order of ASCII code are: '*', '+', '-' and '/'.
-If the division operation is used when the register contains a zero, the program will give an error and terminate with a zero value in the register.
 

Constraints

-s and t will be between 1 and 1000000000 (10^9), inclusive.
 

Examples

0)
    
7
392
Returns: "+*+"
The program executes as follows:
 Reg | Ins | Res
-----+-----+-----
   7 |  +  |  14
  14 |  *  | 196
 196 |  +  | 392
1)
    
7
256
Returns: "/+***"
2)
    
4
256
Returns: "**"
3)
    
7
7
Returns: ""
A trivial program.
4)
    
7
9
Returns: ":-("
No solution.
5)
    
10
1
Returns: "/"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TwoSidedCards

Graph Theory, Math



Used in:

SRM 472

Used as:

Division I Level Two

Writer:

rng_58

Testers:

PabloGilberto , ivan_metelsky , Chmel_Tolstiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10947

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14154&pm=10947

Problem Statement

    There are N cards which are initially blank. First, Taro writes a distinct number between 1 and N, inclusive, on the front side of each card. The number he writes on the i-th card is taro[i]. Then, Hanako turns over all the cards and writes a distinct number between 1 and N, inclusive, on the back side of each card. The number she writes on the i-th card is hanako[i].



Now you must determine the number of distinct ways that the N cards can be arranged in a row. The cards can be placed in any order and each card can be oriented so that either its front side or back side is displayed. Two arrangements are considered distinct if the i-th card in the row shows a different number in one arrangement than it does it in the other. Return the number of distinct possible arrangements, modulo 1,000,000,007.
 

Definition

    
Class:TwoSidedCards
Method:theCount
Parameters:int[], int[]
Returns:int
Method signature:int theCount(int[] taro, int[] hanako)
(be sure your method is public)
    
 

Constraints

-N will be between 1 and 50, inclusive, where N is the number of elements in taro.
-Each element of taro will be between 1 and N, inclusive.
-taro will contain no duplicate elements.
-hanako will contain exactly N elements.
-Each element of hanako will be between 1 and N, inclusive.
-hanako will contain no duplicate elements.
 

Examples

0)
    
{1, 2, 3}
{1, 3, 2}
Returns: 12
If the front side of each card is displayed, the cards will be (1,2,3), and you can get (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), (3,2,1) by changing the order.

If the back side of the second card is displayed, the cards will be (1,3,3), and you can get (1,3,3), (3,1,3), (3,3,1) by changing the order.

If the back side of the third card is displayed, the cards will be (1,2,2), and you can get (1,2,2), (2,1,2), (2,2,1) by changing the order.

If the back sides of both the second and third cards are displayed, the cards will be (1,3,2), and you can get (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), (3,2,1) by changing the order.



In total, there are 12 possibilities: (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), (3,2,1), (1,3,3), (3,1,3), (3,3,1), (1,2,2), (2,1,2), (2,2,1).
1)
    
{1, 2, 3}
{1, 2, 3}
Returns: 6
You can make 123, 132, 213, 231, 312, 321.
2)
    
{1, 2}
{2, 1}
Returns: 4
You can make 11, 12, 21, 22.
3)
    
{5, 8, 1, 2, 3, 4, 6, 7}
{1, 2, 3, 4, 5, 6, 7, 8}
Returns: 2177280
4)
    
{41, 22, 17, 36, 26, 15, 10, 23, 33, 48, 49, 9, 34, 6, 21, 2, 46, 16, 25, 3, 24, 13, 40, 37, 35,
50, 44, 42, 31, 12, 29, 7, 43, 18, 30, 19, 45, 32, 39, 14, 8, 27, 1, 5, 38, 11, 4, 20, 47, 28}
{19, 6, 23, 35, 17, 7, 50, 2, 33, 36, 12, 31, 46, 21, 30, 13, 47, 22, 44, 4, 25, 24, 3, 15, 20,
48, 10, 28, 26, 18, 5, 45, 49, 16, 40, 42, 43, 14, 1, 37, 29, 8, 41, 38, 9, 11, 34, 32, 39, 27}
Returns: 529165844

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SnowPlow

Graph Theory, Simple Math



Used in:

TCO10 Round 2

Used as:

Division I Level One

Writer:

misof

Testers:

PabloGilberto , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10946

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14280&pm=10946

Problem Statement

    

Even though it is June, the city of SnowVille is facing some serious trouble: last night, lots of snow covered all the roads in the city.

The road network looks as follows: There are N important places in the city. The places are labeled 0 through N-1. Each road in the city connects two of these places. Each pair of places is connected by at most one road. Each road can contain one or more car lanes. Each road is bidirectional and the number of lanes is the same for both directions.

Sadly, all the snow plows except for one were already decommissioned for the summer. The one snow plow that is still available is in a depot at place 0.

Whenever the snow plow drives along a road, it is able to clean a single lane going in the direction in which it travels. Hence if you want to clean an entire road with K lanes going in each direction, the snow plow must drive along this road at least K times in each direction.

You are given a String[] roads that describes the road network: If there is no road between places i and j, character j of element i of roads is '0'. The maximum number of lanes a road can have in each direction is 9. If there is a road with k lanes in each direction, character j of element i of roads is 'k' (that is, '1' if there is one lane, '2' if there are two lanes, etc.)

Traversing a single lane of any single road takes the snow plow exactly one minute. Return the least number of minutes in which the snow plow can clean all lanes on all roads. If cleaning all lanes on all roads is impossible, return -1 instead.

 

Definition

    
Class:SnowPlow
Method:solve
Parameters:String[]
Returns:int
Method signature:int solve(String[] roads)
(be sure your method is public)
    
 

Notes

-The snow plow is allowed to drive along a lane it already cleared.
-The road network does not have to be planar.
 

Constraints

-The number of places N will be between 2 and 50, inclusive.
-roads will contain exactly N elements.
-Each element of roads will contain exactly N characters.
-Each character of each element of roads will be between '0' and '9', inclusive.
-roads will be symmetric, i.e., for each i and j: character i of element j of roads will be equal to character j of element i of roads.
-For each i, character i of element i of roads will be '0'.
 

Examples

0)
    
{"010000",
 "101000",
 "010100",
 "001010",
 "000101",
 "000010"}
Returns: 10
The important places are connected as follows: 0-1-2-3-4-5. The only optimal solution is for the snow plow to travel from 0 to 5 and back.
1)
    
{"010000",
 "101000",
 "010100",
 "001020",
 "000201",
 "000010"}
Returns: 12
This time the road between places 3 and 4 has two lanes in each direction. One possible optimal schedule for the snow plow is to visit the places in the order 0,1,2,3,4,5,4,3,4,3,2,1,0, each time using a new lane.
2)
    
{"031415",
 "300000",
 "100000",
 "400000",
 "100000",
 "500000"}
Returns: 28
This time the snow plow can clean all lanes simply by going back and forth between 0 and each of the neighboring places a suitable number of times.
3)
    
{"0100",
 "1000",
 "0001",
 "0010"}
Returns: -1
There is no way to reach the road 2-3, so clearly there is no solution.
4)
    
{"0101",
 "1001",
 "0000",
 "1100"}
Returns: 6
In this case the road network consists of the roads 0-1, 0-3, and 1-3. It can be cleared for example by doing a circle in one direction (0-1-3-0) followed by a circle in the other direction. Note that place 2 remains unvisited.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Planarity

Geometry



Used in:

TCO10 Round 1

Used as:

Division I Level One

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10942

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14272&pm=10942

Problem Statement

    You are given a graph to be drawn on the plane. All edges of the graph are drawn as straight lines. Your task is to arrange the vertices of the graph so that the number of intersecting pairs of edges is minimized.

Implementation Details

Your code should implement one method untangle(int V, int[] edges). The parameters of this method describe the graph in the following way: V is the number of vertices in the graph, and (edges[2*j], edges[2*j+1]) are the indices of vertices which form j-th edge. You have to return a int[] which contains the coordinates of the vertices. Elements 2*i and (2*i+1) of your return should contain the x- and y-coordinates of i-th vertex, respectively.

Test Case Generation

The number of vertices V is chosen between 10 and 100, inclusive. V vertices are placed at distinct random integral points within 700x700 square. A hidden parameter alpha is chosen as a double between 1 and 3. After this the number of edges E is chosen between 2*V and 5*V-1, inclusive. The edges themselves are chosen one by one: each next edge is chosen randomly from the list of unconnected pairs of vertices. Each pair can be chosen with the probability proportional to DIST-alpha, where DIST is the distance between vertices of the pair.

Scoring

Your score for a test case will be the number of pairs of intersecting edges, increased by 1. Two edges intersect each other if they have at least one common point, unless this point is an endpoint of both edges. Your overall score will be calculated in the following way: for each test case you get 1 point for each competitor you beat on this test case (i.e., your score on a test case is less than this competitor's) and 0.5 points for each competitor you tie with (a tie with yourself is not counted); finally, the sum of points is divided by (the number of competitors - 1).

Tools

A visualization tool is provided for offline testing. It also allows manual play.
 

Definition

    
Class:Planarity
Method:untangle
Parameters:int, int[]
Returns:int[]
Method signature:int[] untangle(int V, int[] edges)
(be sure your method is public)
    
 

Notes

-The memory limit is 1024 MB and the time limit is 10 seconds per test case (which includes only time spent in your code). There is no explicit code size limit.
-There are 10 example test cases and 100 full submission test cases.
-Invalid return of any kind (wrong number of elements, invalid coordinates or coinciding vertices) results in zero score for that test case, and doesn't contribute to the overall score.
-See visualizer source for the exact details of generation process and checking whether two edges intersect.
-When V = 10, the number of edges E is reduced to 45 whenever E exceeds 45.
 

Constraints

-Your return must contain exactly 2*V elements.
-Each element of your return must be between 0 and 699, inclusive.
-All vertices locations in your return must be distinct.
 

Examples

0)
    
"1"
Returns: "seed = 1
V = 10
E = 42
alpha = 2.7431439830828896
"
1)
    
"2"
Returns: "seed = 2
V = 23
E = 61
alpha = 1.3799845315969623
"
2)
    
"3"
Returns: "seed = 3
V = 99
E = 413
alpha = 1.1150135028877757
"
3)
    
"4"
Returns: "seed = 4
V = 52
E = 207
alpha = 2.1909318594639484
"
4)
    
"5"
Returns: "seed = 5
V = 83
E = 308
alpha = 2.825971462902503
"
5)
    
"6"
Returns: "seed = 6
V = 34
E = 89
alpha = 1.0386470180784189
"
6)
    
"7"
Returns: "seed = 7
V = 98
E = 431
alpha = 1.6724759405620613
"
7)
    
"8"
Returns: "seed = 8
V = 49
E = 208
alpha = 2.626817509760431
"
8)
    
"9"
Returns: "seed = 9
V = 55
E = 161
alpha = 1.8448823389444475
"
9)
    
"10"
Returns: "seed = 10
V = 84
E = 405
alpha = 1.9578917178952873
"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TwoRegisters

Math, Search



Used in:

TCO10 Round 1

Used as:

Division I Level Two

Writer:

soul-net

Testers:

PabloGilberto , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10937

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14279&pm=10937

Problem Statement

    

You have a very simple computer whose memory consists only of two registers X and Y. Each of them can store a positive integer. The computer is so simple that it only has two different instructions (between brackets is the name of each instruction):

[X] X := X + Y
[Y] Y := X + Y

As you may have imagined, both instructions compute the sum of both registers and store the result in one of them, overwriting its previous content. A program for this computer is simply a sequential list of zero or more instructions. When a program starts in this computer, both registers are initialized to 1. For instance, if the program is "XXYYX" then the following happens:

  X | Y | ins | execute
----+---+-----+------------
  1 | 1 | [X] | X := X + Y
----+---+-----+------------
  2 | 1 | [X] | X := X + Y
----+---+-----+------------
  3 | 1 | [Y] | Y := X + Y
----+---+-----+------------
  3 | 4 | [Y] | Y := X + Y
----+---+-----+------------
  3 | 7 | [X] | X := X + Y
----+---+-----+------------
 10 | 7 |

You will be given an int r. Return the shortest program for the described computer that makes register X end with value r. Register Y may contain any value. If there are several such programs, return the one that comes earliest lexicographically.

 

Definition

    
Class:TwoRegisters
Method:minProg
Parameters:int
Returns:String
Method signature:String minProg(int r)
(be sure your method is public)
    
 

Notes

-A String comes lexicographically earlier than another one of the same length if and only if it contains a letter closer the beginning of the alphabet in the first position at which they differ.
 

Constraints

-r will be between 1 and 1000000 (106), inclusive.
 

Examples

0)
    
10
Returns: "XXYYX"
The example in the problem statement.
1)
    
3
Returns: "XX"
2)
    
20
Returns: "XYYYYXX"
3)
    
34
Returns: "XYXYXYX"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

EqualizeStrings

Greedy



Used in:

TCO10 Round 1

Used as:

Division I Level One

Writer:

soul-net

Testers:

PabloGilberto , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10933

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14279&pm=10933

Problem Statement

    

You have two Strings, s and t, and you want them to be equal. You can change individual letters in the Strings, but you cannot add or remove letters. In a single move, you can change any one letter in one String to the letter that comes directly before or after it in the alphabet. The alphabet wraps around, so you can also change 'a' to 'z' or 'z' to 'a'. You want to make the two Strings equal using the minimum possible number of moves. Return the resulting String. If there are multiple answers, return the one that comes earliest alphabetically.

 

Definition

    
Class:EqualizeStrings
Method:getEq
Parameters:String, String
Returns:String
Method signature:String getEq(String s, String t)
(be sure your method is public)
    
 

Notes

-A String comes earlier lexicographically than another one of the same length if and only if it has a character closer to the beginning of the alphabet in the first position at which they differ.
 

Constraints

-s will contain between 1 and 50 characters, inclusive.
-s and t will contain the same number of characters.
-Each character of s and t will be a lowercase letter ('a'-'z').
 

Examples

0)
    
"cat"
"dog"
Returns: "caa"
Use 1 move to change 'd' to 'c', 12 moves to change 'o' to 'a', 6 moves to change 'g' to 'a' and 7 moves to change 't' to 'a' for a total of 26 moves to get both Strings equal to "caa".
1)
    
"abcdefghijklmnopqrstuvwxyz"
"bcdefghijklmnopqrstuvwxyza"
Returns: "abcdefghijklmnopqrstuvwxya"
Change every letter in t to its previous letter in the alphabet, using exactly one move per letter, with the exception of the last character; it's preferable to change the 'z' in s to 'a' to obtain a lexicographically earlier solution.
2)
    
"programmingcompetitionsrule"
"programmingcompetitionsrule"
Returns: "programmingcompetitionsrule"
If both strings are equal, then you don't need any moves.
3)
    
"topcoderopen"
"onlinerounds"
Returns: "onlcndaoondn"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CuttingGlass

Geometry, Graph Theory, Simulation



Used in:

TCO10 Qual 3

Used as:

Division I Level Three

Writer:

misof

Testers:

PabloGilberto , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10929

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14278&pm=10929

Problem Statement

    

You have a machine that cuts glass panes using a robotic arm with a diamond point at the end.

The input to the machine is a rectangular piece of glass with width W and height H. The machine has a coordinate system with point (0,0) in one corner of the glass pane and (W,H) in the opposite corner. In the beginning, the diamond point is positioned at (startx,starty). Then the machine executes a given program.

The program is given as a String[] program. Concatenate the elements of program to get one long string that describes the program. Each character in the program describes one movement of the diamond point: 'L' decreases its x-coordinate, 'R' increases its x-coordinate, 'U' decreases its y-coordinate and 'D' increases its y-coordinate by 1. During all movements, the diamond point cuts the glass.

Once the cutting is over, the glass may fall apart into multiple pieces. Compute and return their count.

 

Definition

    
Class:CuttingGlass
Method:pieces
Parameters:int, int, int, int, String[]
Returns:int
Method signature:int pieces(int W, int H, int startx, int starty, String[] program)
(be sure your method is public)
    
 

Constraints

-W will be between 1 and 1000, inclusive.
-H will be between 1 and 1000, inclusive.
-startx will be between 0 and W, inclusive.
-starty will be between 0 and H, inclusive.
-program will contain between 1 and 50 elements, inclusive.
-Each element of program will contain between 1 and 50 characters, inclusive.
-Each character in each element of program will be one of 'L', 'R', 'U', and 'D'.
-The program will be such that the diamond point never leaves the glass pane, but it may touch the boundary and even cut along the boundary.
 

Examples

0)
    
100
100
50
50
{"ULDR"}
Returns: 2
This program cuts out a small square piece from a large plate.
1)
    
10
10
3
4
{"UDUDUDUDUDU"}
Returns: 1
After this program is executed, there will be a short cut on the glass pane, but it will still be in one piece.
2)
    
3
3
0
0
{"RDDDUUU","RDDDUUU","R","DLLLRRR","DLLL"}
Returns: 9
This program cuts a 3x3 glass pane into nine separate 1x1 squares.
3)
    
5
3
5
3
{"LULLULLU"}
Returns: 2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheMoviesLevelTwoDivTwo

Simple Search, Iteration



Used in:

SRM 469

Used as:

Division II Level Two

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , Andrew_Lazarev , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10901

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14152&pm=10901

Problem Statement

    John has decided to watch some horror movies tonight. He has a collection of N scary movies, numbered 0 to N-1, inclusive. The lengths of the movies are given in the int[] length, where the i-th element is the length in minutes of movie i.



However, John is very tired, so it is possible for him to fall asleep while watching a movie. The only way he can stay awake is to maintain a certain level of being scared. He has a "scare level" which is a real number initially equal to 74. His scare level will continuously decrease at a speed of 1 per minute. For example, after 6 seconds, it will go down by 0.1. Once this level falls below -0.5, John will fall asleep. Each of John's movies has exactly one scary moment. Once John sees this moment, his scare level will instantly increase by 47. The scary moments are given in the int[] scary. In movie i, the scary moment will occur exactly scary[i] minutes after the beginning of the movie.



John would like to determine the best order in which to watch the movies. Each order can be described by an int[] containing N distinct numbers between 0 and N-1, inclusive. The first element is the number of the first movie he watches, the second element is the number of the second movie he watches, and so on. Once a movie is finished playing, the next one starts immediately. If John falls asleep while watching a movie, he won't be able to watch the rest of the current movie, and he won't be able to watch any of the movies that he planned to watch after the current movie. Among all the possible orders, return the one that allows John to watch as many movies as possible in their entirety (i.e., from beginning to end) before falling asleep. If there are several such orders, return the one that comes earliest lexicographically.
 

Definition

    
Class:TheMoviesLevelTwoDivTwo
Method:find
Parameters:int[], int[]
Returns:int[]
Method signature:int[] find(int[] length, int[] scary)
(be sure your method is public)
    
 

Notes

-A int[] A comes before a int[] B lexicographically if A contains a smaller number at the first index where they differ.
 

Constraints

-length will contain between 1 and 7 elements, inclusive.
-length and scary will contain the same number of elements.
-Each element of length will be between 2 and 474, inclusive.
-The i-th element of scary will be between 1 and length[i] - 1, inclusive.
 

Examples

0)
    
{100, 50}
{1, 1}
Returns: {0, 1 }
There are two possible playlists, and John can watch either one in its entirety without falling asleep.
1)
    
{100, 50}
{1, 49}
Returns: {1, 0 }
The only way John can see all the movies is to start with the last one.
2)
    
{100, 100, 100, 100}
{77, 76, 75, 74}
Returns: {3, 0, 1, 2 }
If John starts with the last movie, he will fall asleep during the second movie. If he starts with any other movie, he will fall asleep during the first movie.
3)
    
{100}
{99}
Returns: {0 }
Here John has no choice at all.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheMoviesLevelTwoDivOne

Dynamic Programming



Used in:

SRM 469

Used as:

Division I Level Two

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , Andrew_Lazarev , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10900

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14152&pm=10900

Problem Statement

    John has decided to watch some horror movies tonight. He has a collection of N scary movies, numbered 0 to N-1, inclusive. The lengths of the movies are given in the int[] length, where the i-th element is the length in minutes of movie i.



However, John is very tired, so it is possible for him to fall asleep while watching a movie. The only way he can stay awake is to maintain a certain level of being scared. He has a "scare level" which is a real number initially equal to 74. His scare level will continuously decrease at a speed of 1 per minute. For example, after 6 seconds, it will go down by 0.1. Once this level falls below -0.5, John will fall asleep. Each of John's movies has exactly one scary moment. Once John sees this moment, his scare level will instantly increase by 47. The scary moments are given in the int[] scary. In movie i, the scary moment will occur exactly scary[i] minutes after the beginning of the movie.



John would like to determine the best order in which to watch the movies. Each order can be described by an int[] containing N distinct numbers between 0 and N-1, inclusive. The first element is the number of the first movie he watches, the second element is the number of the second movie he watches, and so on. Once a movie is finished playing, the next one starts immediately. If John falls asleep while watching a movie, he won't be able to watch the rest of the current movie, and he won't be able to watch any of the movies that he planned to watch after the current movie. Among all the possible orders, return the one that allows John to watch as many movies as possible in their entirety (i.e., from beginning to end) before falling asleep. If there are several such orders, return the one that comes earliest lexicographically.
 

Definition

    
Class:TheMoviesLevelTwoDivOne
Method:find
Parameters:int[], int[]
Returns:int[]
Method signature:int[] find(int[] length, int[] scary)
(be sure your method is public)
    
 

Notes

-A int[] A comes before a int[] B lexicographically if A contains a smaller number at the first index where they differ.
 

Constraints

-length will contain between 1 and 20 elements, inclusive.
-length and scary will contain the same number of elements.
-Each element of length will be between 2 and 474, inclusive.
-The i-th element of scary will be between 1 and length[i] - 1, inclusive.
 

Examples

0)
    
{100, 50}
{1, 1}
Returns: {0, 1 }
There are two possible playlists, and John can watch either one in its entirety without falling asleep.
1)
    
{100, 50}
{1, 49}
Returns: {1, 0 }
The only way John can see all the movies is to start with the last one.
2)
    
{100, 100, 100, 100}
{77, 76, 75, 74}
Returns: {3, 0, 1, 2 }
If John starts with the last movie, he will fall asleep during the second movie. If he starts with any other movie, he will fall asleep during the first movie.
3)
    
{100}
{99}
Returns: {0 }
Here John has no choice at all.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

VacationTours

Graph Theory



Used in:

TCO10 Round 1

Used as:

Division I Level Three

Writer:

soul-net

Testers:

PabloGilberto , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10897

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14279&pm=10897

Problem Statement

    

A travel agent is organizing tours for a group of people. He is charging a fixed fee to the whole group for each tour they take. The company policy, however, forces him to make each tour completely different from other tours because tourists don't want to see the same sight twice.

Each tour the agent plans starts at the group's hotel, consists of a sequence of distinct sights and ends at the hotel. The agent has managed to get the best price on transportation from the hotel to each of the sights, and between the sights. All transportation is directed, which means the cost to travel from A to B may be different from the cost to travel from B to A. The overall cost of a tour is the sum of all the transportation costs in the tour.

You will be given the information the agent has. The fee will be given as an int. The transportation costs between sights or between each sight and the hotel are given in two String[]s, c and d. Character j of element i of c and d give the first and second digit, respectively, in base-64 coding (explained in the notes), of the cost to the agency of transporting the whole group from point i to point j. Point 0 is always the hotel, while all the other points are the sights. You have to return the maximum income the agency can make by allocating tours. The income will be the fee multiplied by the number of tours, minus the total costs of all transportation needed. See the examples for further clarification.

 

Definition

    
Class:VacationTours
Method:getIncome
Parameters:String[], String[], int
Returns:int
Method signature:int getIncome(String[] c, String[] d, int fee)
(be sure your method is public)
    
 

Notes

-If c is the first digit and d is the second digit in base-64 coding, then the value is c*64+d, where c and d are translated to a number between 0 and 63, inclusive, as follows:
  • Uppercase letters 'A' to 'Z' have values 0 to 25, respectively
  • Lowercase letters 'a' to 'z' have values 26 to 51, respectively
  • Digits '0' to '9' have values 52 to 61, respectively
  • '+' has value 62 and '/' has value 63
-Transportation costs are not necessarily reflexive, and do not necessarilly follow the triangle inequality. When the group needs to be transported from point i to point j, the agent has to do this directly, even if traveling through one or more intermediate points would result in a lower cost. See examples for further clarification.
 

Constraints

-fee will be between 1 and 10000, inclusive.
-c will contain between 2 and 50 elements, inclusive.
-d will contain the same number of elements as c.
-Each element of c and d will contain exactly N characters, where N is the number of elements of c.
-Each character of each element of both c and d will be a base-64 coding character, as described in the notes.
-Character i of element i of both c and d will be an uppercase 'A'.
 

Examples

0)
    
{"AAA",
 "AAA",
 "AAA"}
{"ABJ",
 "JAB",
 "BJA"}
15
Returns: 12
The price matrix is as follows:
- 1 9
9 - 1
1 9 -
You can set up two tours stopping at sight 1 and 2 respectively, for a cost of 10 each. You can earn 30=15*2 by doing it, making a total profit of 10. Alternatively, you can set up a single tour that goes to sight 1, then to sight 2, and returns to the hotel with a total cost of only 3. In the second case you can earn only 15, with an overall benefit of 12. The latter is the optimal arrangement.
1)
    
{"AAAA",
 "AAAA",
 "AAAA",
 "AAAA"}
{"AAAA",
 "AAAA",
 "AAAA",
 "AAAA"}
100
Returns: 300
All trips are free, so you must do as many tours as possible (3 in total, one for each sight).
2)
    
{"A//",
 "/A/",
 "//A"}
{"A//",
 "/A/",
 "//A"}
1000
Returns: 0
All possible trips are too expensive to get any benefit, so it's better to do no trips.
3)
    
{"AAA////",
 "/AA/A//",
 "//AA/A/",
 "A//AA//",
 "///AAA/",
 "///A/AA",
 "AA////A"}
{"AKo////",
 "/AU/X//",
 "//AZ/o/",
 "j//AK//",
 "///XAo/",
 "///y/AK",
 "KP////A"}
1000
Returns: 1809

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SequenceMerger

Math, Search, Sorting



Used in:

TCO10 Qual 1

Used as:

Division I Level Three

Writer:

soul-net

Testers:

PabloGilberto , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10887

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14294&pm=10887

Problem Statement

    In this problem, you will be given descriptions of several integer sequences, and you will be required to return elements at certain positions of the union of all the given sequences. The union of several sequences is a sequence containing all the elements of those sequences, sorted in non-decreasing order. For each integer x, the number of occurrences of x in the union is equal to the total number of occurrences of x in all the given sequences. For example, if we are given sequences (3, 2, 2, 3), (1) and (5, 7, 1), their union is the sequence (1, 1, 2, 2, 3, 3, 5, 7).



Each of the given sequences will be an arithmetic sequence, a geometric sequence or an explicit sequence.
  • An arithmetic sequence is described by three positive integers A, B and C. The sequence contains exactly C elements: A, A+B, A+B+B, ..., A+B*(C-1). Formally, the sequence is { A+B*x | x an integer between 0 and C-1, inclusive}.
  • A geometric sequence is described by three positive integers A, B and C. The sequence contains exactly C elements: A, A*B, A*B*B, ..., A*B^(C-1). Formally, the sequence is { A*B^x | x an integer between 0 and C-1, inclusive}.
  • An explicit sequence is just a non-empty sequence of arbitrary positive integers.
Each sequence will be represented as a String, where the first character is 'A', 'G' or 'E', denoting arithmetic, geometric or explicit sequences, respectively. The second character will always be a space. After that is a list of positive integers, where each integer is written with no leading zeroes, consecutive integers are separated by a single space, and there are no leading or trailing spaces. In the case of arithmetic and geometric sequences, this list will always contain exactly three integers, A, B and C, in that order, as described above for each type of sequence. For explicit sequences, the list will contain one or more integers, explicitly representing the members of the sequence.



You will be given a String[] seqs, where each element represents a sequence as described in the previous paragraph, and a int[] positions, which contains a list of 1-based positions. Return a int[] containing the same number of elements as positions, such that its i-th element is the element at position positions[i] of the union of all the sequences in seqs. If the union contains less than positions[i] elements or if the element at position positions[i] of the union is strictly greater than 1000000000 (10^9), the i-th element of the return must be -1 instead. See examples for further clarification.
 

Definition

    
Class:SequenceMerger
Method:getVal
Parameters:String[], int[]
Returns:int[]
Method signature:int[] getVal(String[] seqs, int[] positions)
(be sure your method is public)
    
 

Notes

-The elements of the given sequences don't necessarily fit within 32-bit or 64-bit integer types.
 

Constraints

-positions will contain between 1 and 50 elements, inclusive.
-Each element of positions will be between 1 and 1000000000 (10^9), inclusive.
-seqs will contain between 1 and 50 elements, inclusive.
-Each element of seqs will contain between 3 and 50 characters, inclusive.
-Each element of seqs will be formatted as described in the problem statement.
 

Examples

0)
    
{"E 1 1000000000 1000000001"}
{1,2,3,4}
Returns: {1, 1000000000, -1, -1 }
The sequence here has only 3 elements. The first two elements are returned normally. The element at position 3 is strictly greater than 1000000000, so you must return -1 in that place. There is no element at position 4, so you must also return -1 there.
1)
    
{"A 1 1 10", "G 1 2 4"}
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
Returns: {1, 1, 2, 2, 3, 4, 4, 5, 6, 7, 8, 8, 9, 10, -1 }
The arithmetic sequence is 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. The geometric sequence is 1, 2, 4, 8. Therefore, the resulting sequence is 1, 1, 2, 2, 3, 4, 4, 5, 6, 7, 8, 8, 9, 10.
2)
    
{"A 1000000000 1000000000 1000000000","G 100000000000000000 1000000000000 100000000000000", "E 1000000000000000 10000000 10 1111"}
{1,2,3,4,5,6,7,8,9,10}
Returns: {10, 1111, 10000000, 1000000000, -1, -1, -1, -1, -1, -1 }
Watch out for big numbers.
3)
    
{"G 1 1 999999999", "E 2"}
{1,999999999,1000000000}
Returns: {1, 1, 2 }
A lot of 1s and a 2.
4)
    
{"A 100 341 1524", "G 1 3 45235", "E 653 87 12341 8785 123 543"}
{100000,1,10,10000,100,1000}
Returns: {-1, 1, 441, -1, 28403, 334621 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RabbitJumping

Graph Theory



Used in:

SRM 475

Used as:

Division II Level Three

Writer:

lyrically

Testers:

PabloGilberto , ivan_metelsky , keshav_57

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10882

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14156&pm=10882

Problem Statement

    Rabbits often feel lonely, so when they go out to meet their friends, they jump as quickly as possible.



Rabbit Iris is on an infinitely long straight road. Points on this road are numbered ..., -3, -2, -1, 0, 1, 2, 3, ... from west to east. Iris is at point 0 now, and she is going to meet her friend at point 1,000,000,001. She can only move by jumping, and she can perform two types of jumps: small and large. When she is at point x,
  • By making a small jump, she can move to either point (x + 2) or point (x - 2).
  • By making a large jump, she can move to either point (x + largeJump) or point (x - largeJump).
Unfortunately, the road contains holes, and Iris can never land on a point which contains a hole. You are given a int[] holes containing N * 2 elements. For each i, where 0 <= i < N, all points between holes[i * 2] and holes[i * 2 + 1], inclusive, contain holes.



Iris prefers to perform small jumps because she can do them faster. Return the minimum number of large jumps required to reach point 1,000,000,001. If it is impossible to reach that point, return -1 instead.
 

Definition

    
Class:RabbitJumping
Method:getMinimum
Parameters:int[], int
Returns:int
Method signature:int getMinimum(int[] holes, int largeJump)
(be sure your method is public)
    
 

Notes

-Iris can travel to points with negative numbers and numbers greater than 1,000,000,001.
 

Constraints

-holes will contain between 2 and 50 elements, inclusive.
-holes will contain an even number of elements.
-Each element of holes will be between 1 and 1,000,000,000, inclusive.
-Elements of holes will be in strictly increasing order.
-largeJump will be between 3 and 1,000,000,000, inclusive.
 

Examples

0)
    
{ 1, 2 }
3
Returns: 1
0 => 3 -> 5 -> 7 -> ... -> 999999999 -> 1000000001



Iris needs to make at least one large jump to jump over the holes at points 1 and 2.
1)
    
{ 1, 2 }
4
Returns: -1
Iris can never step on point 1,000,000,001, or any other odd-numbered point.
2)
    
{ 2, 3 }
3
Returns: 3
One solution to reach the goal with 3 large jumps is:



0 -> -2 => 1 => 4 => 7 -> 9 -> 11 -> ... -> 999999999 -> 1000000001
3)
    
{ 2, 17, 21, 36, 40, 55, 59, 74 }
19
Returns: 5
4)
    
{ 187640193, 187640493, 187640738, 187640845, 564588641, 564588679, 
  564588696, 564588907, 605671187, 605671278, 605671288, 605671386, 
  755723729, 755723774, 755723880, 755723920, 795077469, 795077625, 
  795077851, 795078039, 945654724, 945654815, 945655107, 945655323 }
475
Returns: 9

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MallSecurity

Brute Force, Graph Theory, Math



Used in:

Member SRM 468

Used as:

Division I Level Three

Writer:

keshav_57

Testers:

Rustyoldman , ivan_metelsky , mohamedafattah , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10877

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14183&pm=10877

Problem Statement

    The first mall of the kingdom is about to be inaugurated in a few days. The king wants to make sure that the mall is highly secured.



The mall has N floors, numbered 1 to N. Each floor has stations which allow people to enter or leave the floor to which the station belongs. All escalators in the mall begin and end at stations of adjacent floors. To make movement of people easier, super-escalators connect stations in floor 1 to stations in floor N. Each escalator or super-escalator can be used to go upwards as well as downwards. If the i-th floor has Ki stations then the stations are numbered from 1 to Ki. The escalators and super-escalators are constructed in such a way that a person can reach any station from any other station using them.



The king wants to have as many guards in the mall as possible to make it secure. Guards can only be placed at stations and at most 1 guard can be placed at a station. Moreover, the people of the kingdom become panicky if they see more than one guard at a time. Hence, there should be no such escalator (or super-escalator) such that guards are placed at both its end stations.



You are given a String[] escDescription which when concatenated represents a comma (',') separated list of escalators and super-escalators. Every escalator (or super-escalator) is of the form "A B C". If C is less than N, the String represents an escalator from station A of floor C, to station B of floor C+1. If C is equal to N, then the String represents a super-escalator from station A of floor C (= N), to station B of floor 1. Help the king by returning the maximum number of guards he can place in the mall.

 

Definition

    
Class:MallSecurity
Method:maxGuards
Parameters:int, String[]
Returns:int
Method signature:int maxGuards(int N, String[] escDescription)
(be sure your method is public)
    
 

Constraints

-N will be between 10 and 50, inclusive.
-The total number of stations in the mall will not exceed 100.
-escDescription will contain between 1 and 50 elements, inclusive.
-Each element of escDescription will contain between 1 and 50 characters, inclusive.
-The concatenation of the elements of escDescription will be a comma separated list of escalators and super-escalators.
-Each escalator and super-escalator will be given as "A B C" (quotes for clarity), where A, B and C are positive integers with no leading zeros.
-In each escalator and super-escalator description, A will be a valid number of station located on floor C.
-In each escalator and super-escalator description, B will be a valid number of station located on floor C + 1 (or on floor 1, if C = N).
-In each escalator and super-escalator description, C will be between 1 and N, inclusive.
-Each floor will have at least 1 station.
-The stations on each floor will be numbered from 1 to K, inclusive, where K is the total number of stations on this floor.
-Each pair of stations will be connected with at most one escalator or super-escalator.
-It will be possible to reach any station from any other station using escalators and super-escalators.
 

Examples

0)
    
10
{"1 1 1,1 1 2,1 1 3,1 1 4,1 1 5,1 1 6,1 1 7,1 1 8,1 ", 
 "1 9,1 1 10"}
Returns: 5
There are 10 floors and each floor has only one station. The stations on adjacent floors are connected with escalators. The stations on floor 1 and on floor 10 are connected with a super-escalator. You can place 5 guards on stations of the following floors: 1, 3, 5, 7 and 9. Another solution is to place them on floors 2, 4, 6, 8, 10.
1)
    
11
{"1 1 1,1 1 2,1 1 3,1 1 4,1 1 5,1 1 6,1 1 7,1 1 8,1 ", 
 "1 9,1 1 10"}
Returns: 6
This time there are 11 floors and there's no super-escalator. You can place 6 guards on stations of the following floors: 1, 3, 5, 7, 9, 11.
2)
    
10
{"1 1 7,1 2 9,2 1", 
 " 8,1 2 6,1 1 8,1 2 3,1 2 2,2 ", 
 "2 4,1 1 1,2 1 2,3 2 3,1 1 5,2 1 1,4 ", 
 "1 7,1 1 10,3 2 5,1 2 5,3 3 1,", 
 "3 2 8,3 1 2,1 1 3,4 4 2,2", 
 " 4 6,4 2 5,2 3 3,6 4 1,5 2 8,1 3 6,1 3 7,", 
 "4 3 8,1 3 8,5 2 3,4 2 8,2 6 7,1 3 9,", 
 "1 1 4,6 1 1,2 3 1,5 1 5,6 1 8,5 ", 
 "2 2,3 2 10,3 3 9,1 5 2,4 1 1,1 5 10"}
Returns: 25

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MatrixGame

Brute Force, Sorting, String Manipulation



Used in:

SRM 466

Used as:

Division II Level Three

Writer:

Chmel_Tolstiy

Testers:

PabloGilberto , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10861

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14150&pm=10861

Problem Statement

    Alex likes to play the following strange game. He starts with a rectangular NxM grid where each cell contains a '0' (zero) or '1' (one). Rows of the grid are numbered 0 to N-1, inclusive, and columns are numbered 0 to M-1, inclusive. On each move, he chooses two columns in the grid and entirely swaps their content or he chooses two rows in the grid and entirely swaps their content. He can perform an arbitrary large number of moves and there are no restrictions on the order in which he performs moves.



Each NxM grid can be described as a String[] containing N elements. The j-th character in the i-th element of this String[] is the same as the character in row i, column j of the grid. Alex's goal is to achieve such a grid that the corresponding String[] is lexicographically minimal (see notes for exact definition). Since he is always unsure whether the goal has been achieved, you are to write a program that checks it for him. Given a String[] matrix describing the grid that Alex initially has, return the lexicographically smallest String[] that he can produce.
 

Definition

    
Class:MatrixGame
Method:getMinimal
Parameters:String[]
Returns:String[]
Method signature:String[] getMinimal(String[] matrix)
(be sure your method is public)
    
 

Notes

-A String[] A is lexicographically smaller than a String[] B of the same length if it contains a lexicographically smaller String at the first position where they differ.
-A String A is lexicographically smaller than a String B of the same length if it contains a smaller character at the first position where they differ ('0' is smaller than '1').
 

Constraints

-matrix will contain between 1 and 8 elements, inclusive.
-Each element of matrix will contain between 1 and 8 characters, inclusive.
-All elements of matrix will have the same length.
-Each character in matrix will be either '0' or '1'.
 

Examples

0)
    
{"000",
 "000",
 "000"}
Returns: {"000", "000", "000" }
Any move has no effect.
1)
    
{"010",
 "000",
 "110"}
Returns: {"000", "001", "011" }
The following sequence of moves can be used:
010      000      000      000
000  ->  010  ->  001  ->  001
110      110      101      011
2)
    
{"111",
 "111",
 "111"}
Returns: {"111", "111", "111" }
3)
    
{"01010",
 "10101",
 "01010",
 "10101"}
Returns: {"00011", "00011", "11100", "11100" }
4)
    
{"11010100",
 "11110001",
 "00011101",
 "11111111",
 "01110100",
 "10000110",
 "00001001",
 "11010111"}
Returns: 
{"00000011",
"00001111",
"00110100",
"01011100",
"01111101",
"11001100",
"11011001",
"11111111" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

NextHomogeneousStrings

Dynamic Programming



Used in:

SRM 467

Used as:

Division I Level Three

Writer:

vexorian

Testers:

PabloGilberto , misof , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10848

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14151&pm=10848

Problem Statement

    A string is homogeneous if every contiguous substring of length n contains at most d different characters. For a String seed and a long k, the k-th homogeneous string is defined as the k-th element (0-indexed) in the list of all homogeneous strings which have the same length as seed and are lexicographically greater than or equal to seed. Only strings containing all lowercase letters ('a'-'z') should be considered. Return the k-th homogeneous string. If there are less than k+1 strings in this list, return "" instead (quotes for clarity).
 

Definition

    
Class:NextHomogeneousStrings
Method:getNext
Parameters:int, int, String, long
Returns:String
Method signature:String getNext(int d, int n, String seed, long k)
(be sure your method is public)
    
 

Notes

-If A and B are two Strings of the same length, then A comes earlier lexicographically than B if it contains a smaller character at the first position where the Strings differ.
 

Constraints

-n will be between 1 and 9, inclusive.
-d will be between 1 and n, inclusive.
-k will be between 0 and 1000000000000000000 (10^18), inclusive.
-seed will contain between 1 and 50 characters, inclusive.
-seed will contain at least n characters.
-seed will contain only lowercase letters ('a'-'z').
 

Examples

0)
    
1
2
"aaa"
3
Returns: "ddd"
The condition n=2 and d=1 requires no two consecutive characters to be different. The only homogeneous strings in this case would be: "aaa", "bbb", "ccc", "ddd", ... , "zzz". "ddd" is the fourth one.
1)
    
2
3
"abc"
0
Returns: "aca"
2)
    
2
4
"ttrrzz"
6
Returns: "ttsssc"
3)
    
6
8
"txyaaxaassaaaarghjsdohasdghususdidisisdodo"
10000000000000000
Returns: "txyaaxaassaaaarghjsgaaaaaaaaadntffiniqrddy"
4)
    
2
5
"zzzzzaa"
100
Returns: ""
In this case, there are 25 homogeneous strings that follow the pattern "zzzzzXX", where X is any letter different from 'z'. There are another 25 homogeneous strings that follow the pattern "zzzzzXz". Finally, there are 26 homogeneous strings that begin with "zzzzzz". In total, there are only 25+25+26 = 76 homogeneous strings that are lexicographically greater than or equal to "zzzzzaa".

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheLuckyNumbersLevelTwo

Recursion, Sorting



Used in:

TCHS10 Championship Round

Used as:

Division I Level Two

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , ivan_metelsky , StevieT

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10833

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14247&pm=10833

Problem Statement

    

The digits 4 and 7 are lucky digits, and all other digits are unlucky. A second level lucky number is a positive integer whose decimal representation contains either all 4's or all 7's. John and Brus have a set of integers, and they would like to find the subset whose sum is a second level lucky number.

You are given int[] numbers, the set of integers that John and Brus have. Return a int[] containing the subset whose sum is a second level lucky number. The return value must be sorted in ascending order. If there are multiple possible return values, return the one with the largest sum. If there is a tie, return the one that comes earliest lexicographically. A int[] a1 comes before a int[] a2 lexicographically if a1 contains a smaller number at the first index where they differ. If there are no possible subsets, return an empty int[] instead.

 

Definition

    
Class:TheLuckyNumbersLevelTwo
Method:find
Parameters:int[]
Returns:int[]
Method signature:int[] find(int[] numbers)
(be sure your method is public)
    
 

Constraints

-numbers will contain between 1 and 34 elements, inclusive.
-Each element of numbers will be between 1 and 1,000,000,000, inclusive.
-All elements in numbers will be distinct.
 

Examples

0)
    
{1, 2, 3, 4}
Returns: {1, 2, 4 }
Here it's possible to get two second level lucky numbers - 4 and 7. There are two subsets with a sum of 7 - {3, 4} and {1, 2, 4}. We will choose the last one because it is lexicographically smaller.
1)
    
{12, 43, 29}
Returns: { }
There are no subsets whose sum is a second level lucky number.
2)
    
{4, 7}
Returns: {7 }
3)
    
{41, 2, 28, 44, 7, 42, 21}
Returns: {7, 28, 42 }
4)
    
{15, 10, 28, 3, 13, 27, 7}
Returns: {7, 15, 27, 28 }
5)
    
{18, 45, 6}
Returns: { }
6)
    
{34, 20, 26, 28, 33, 23, 44, 40, 25, 10, 36, 14, 7, 29, 21, 27, 17, 13, 19, 24, 32, 41, 31}
Returns: {7, 10, 13, 14, 17, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 31, 32, 34, 44 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheSequencesLevelTwo

Greedy, Sorting



Used in:

TCHS10 Round 1

Used as:

Division I Level Two

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , ivan_metelsky , StevieT

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10818

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14224&pm=10818

Problem Statement

    

When John and Brus were high school students, they liked to investigate integer sequences. Once, John wrote down a sequence containing distinct positive integers. Brus wanted to reorder the elements of the sequence in such a way that the following condition held for all j, where 0 < j < n-1, and n is the number of elements in the sequence: The (j-1)-th and the (j+1)-th elements of the sequence are either both less than the j-th element or both greater than the j-th element. In other words, except for the first and last elements, the two immediate neighbors of each element must be either both greater than or both less than that element.

You are given a int[] sequence containing John's original sequence. Return the sequence after Brus reordered it. If there are several possible answers, return the one that comes first lexicographically. Sequence A comes before sequence B lexicographically if A contains a smaller value at the first index where they differ.

 

Definition

    
Class:TheSequencesLevelTwo
Method:find
Parameters:int[]
Returns:int[]
Method signature:int[] find(int[] sequence)
(be sure your method is public)
    
 

Notes

-There will always be at least one way for Brus to achieve his goal.
 

Constraints

-sequence will contain between 1 and 50 elements, inclusive.
-Each element of sequence will be between 1 and 1,000,000,000, inclusive.
-All elements in sequence will be distinct.
 

Examples

0)
    
{1, 5, 10}
Returns: {1, 10, 5 }
There are four possible ways for Brus to reorder the elements - {1, 10, 5}, {5, 1, 10}, {5, 10, 1} and {10, 1, 5}. He will choose the first of them.
1)
    
{47}
Returns: {47 }
This sequence contains only a single element, so it already satisfies Brus's goal.
2)
    
{7, 2, 5, 4}
Returns: {2, 5, 4, 7 }
This sequence already meets Brus's requirements, but he can reorder the elements to get another sequence that comes earlier lexicographically.
3)
    
{51, 49, 97, 9, 10, 89, 90, 41, 58}
Returns: {9, 41, 10, 51, 49, 89, 58, 97, 90 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Cryptography

Encryption/Compression, Math, Sorting



Used in:

SRM 480

Used as:

Division II Level One

Writer:

dolphinigle

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10814

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14159&pm=10814

Problem Statement

    TopCoder Security Agency (TSA, established today) has just invented a new encryption system! This encryption system takes as its input a list of numbers to encrypt.



You work at TSA and your task is to implement a very important part of the encryption process. You are allowed to pick one number in the input list and increment its value by 1. This should be done in such way that the product of all numbers in the list after this change becomes as large as possible.



Given the list of numbers as int[] numbers, return the maximum product you can obtain. It is guaranteed that the return value will not exceed 2^62.
 

Definition

    
Class:Cryptography
Method:encrypt
Parameters:int[]
Returns:long
Method signature:long encrypt(int[] numbers)
(be sure your method is public)
    
 

Constraints

-numbers will contain between 2 and 50 elements, inclusive.
-Each element of numbers will be between 1 and 1000, inclusive.
-The return value will not exceed 2^62.
 

Examples

0)
    
{1,2,3}
Returns: 12
If we increment the first number, we get 2*2*3 = 12. If we increment the second, we get 1*3*3 = 9. If we increment the third, we get 1*2*4 = 8. Hence, the correct return value is 12.
1)
    
{1,3,2,1,1,3}
Returns: 36
The elements of numbers are not necessarily unique.
2)
    
{1000,999,998,997,996,995}
Returns: 986074810223904000
The answer may be very big, but will not exceed 2^62.
3)
    
{1,1,1,1}
Returns: 2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BatchSystem

Greedy



Used in:

SRM 481

Used as:

Division II Level Three

Writer:

vexorian

Testers:

PabloGilberto , ivan_metelsky , Chmel_Tolstiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10808

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14234&pm=10808

Problem Statement

    In the past, whole organizations depended on a single, big computer to do all the computational work. In a particular case, a computer has a list of pending jobs which is described by int[] duration and String[] user. There are n pending jobs and each job is described by these two arrays. For the i-th job, duration[i] is the total time in minutes required to complete the job and user[i] is a string that identifies the user that requested that job. A user may request multiple jobs. The computer may only process one job at a time. The waiting time for a user is defined as the time that this user has to wait before all of the jobs (s)he requested are finished. Your program must schedule the jobs in such a way that the average waiting time over all users is minimized.



Return a int[] containing the 0-based indices of the n jobs in the order in which they should be processed. If there are multiple possible results, return the one that comes first lexicographically.
 

Definition

    
Class:BatchSystem
Method:schedule
Parameters:int[], String[]
Returns:int[]
Method signature:int[] schedule(int[] duration, String[] user)
(be sure your method is public)
    
 

Notes

-The lexicographically earlier of two int[]s of the same length is the one that has the smaller element in the first position at which they differ.
-User names are case sensitive. A user named "Bob" is different from a user named "bob". See example 3 for clarification.
 

Constraints

-duration will contain between 1 and 50 elements, inclusive.
-user will contain the same number of elements as duration.
-Each element of duration will be between 1 and 1000000000, inclusive.
-Each element of user will contain between 1 and 50 characters, inclusive.
-Each element of user will contain only letters ('a'-'z','A'-'Z') and at most one space character that will not be a leading or trailing space.
 

Examples

0)
    
{400, 100, 100, 100}
{"Danny Messer", "Stella Bonasera", "Stella Bonasera", "Mac Taylor"}
Returns: {3, 1, 2, 0 }
In total, Mac Taylor will have to wait 100 minutes, Stella Bonasera 300 minutes and Danny Messer 700 minutes. The best average time is approximately 366.66 minutes.
1)
    
{200, 200, 200}
{"Gil", "Sarah", "Warrick"}
Returns: {0, 1, 2 }
2)
    
{100, 200, 50}
{"Horatio Caine", "horatio caine", "YEAAAAAAH"}
Returns: {2, 0, 1 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TreesCount

Dynamic Programming, Graph Theory



Used in:

Member Single Round Match 474

Used as:

Division I Level Two

Writer:

maksay

Testers:

Rustyoldman , ivan_metelsky , mohamedafattah , it4.kp , K.A.D.R

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10805

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14185&pm=10805

Problem Statement

    Little Dazdraperma likes graphs a lot. Recently she invented a new game for one person with graphs. She is given a connected undirected graph with N vertices numbered 0 to N-1, inclusive (see the notes for definitions of all unclear terms from graph theory). Each edge of the graph is labeled with a positive integer length. She tries to remove some edges (possibly 0) so that the resulting graph satisfies the following conditions:
  • The graph that remains is a tree with exactly N-1 edges.
  • For each v, 0 < v < N, the shortest distance between vertex 0 and vertex v is the same in the resulting graph and in the initial graph.
Dazdraperma wonders how many different resulting graphs that satisfy these conditions she can obtain. Two graphs are considered different if there are two different vertices such that one of the graphs contains an edge between these two vertices and another graph doesn't contain an edge between them.



You are given the representation of the initial graph as a String[] graph. This String[] contains exactly N elements and each element contains exactly N characters. The j-th character in the i-th element will be '0' if there is no edge between vertices i and j. Otherwise, it will be a character between '1' and '9' representing the length of the edge between vertices i and j.



Return the number of possible resulting graphs modulo 1000000007.
 

Definition

    
Class:TreesCount
Method:count
Parameters:String[]
Returns:int
Method signature:int count(String[] graph)
(be sure your method is public)
    
 

Notes

-For the purpose of this problem, an undirected graph can be treated as a set of vertices and a set of edges, where each edge establishes a bidirectional connection between two different vertices.
-A path between two different vertices A and B in a graph G is a sequence of 2 or more vertices v[0] = A, v[1], ..., v[L-1] = B, such that there's an edge in G between each two adjacent vertices in this sequence. A path is said to consist of edges between v[i] and v[i+1], where 0 ≤ i < L-1. The length of a path is the sum of lengths of all edges it consists of.
-The path between vertices A and B in a graph G that has the minimum possible length is called the shortest path between them. The length of this path is called the shortest distance between A and B.
-A graph G is connected if there's a path between each two different vertices of G.
-A graph G is a tree if it is connected and contains exactly V-1 edges, where V is the total number of vertices in G.
 

Constraints

-graph will contain between 2 and 50 elements, inclusive.
-Each element of graph will contain the same number of characters as the number of elements in graph.
-Each character in each element of graph will be between '0' and '9', inclusive.
-For each i, the i-th character of i-th element of graph will always be '0'.
-For each i and j, the i-th character of j-th element of graph will always be equal to the j-th character of i-th element of graph.
-graph will represent a connected graph.
 

Examples

0)
    
{"01",
 "10"}
Returns: 1
The graph is already a tree, so the answer is 1.
1)
    
{"011",
 "101",
 "110"}
Returns: 1
The only possibility is to delete the edge between vertices 1 and 2.
2)
    
{"021",
 "201",
 "110"}
Returns: 2
You can either delete the edge between vertices 1 and 2 or the edge between vertices 0 and 1.
3)
    
{"0123",
 "1012",
 "2101",
 "3210"}
Returns: 6
More possibilities.
4)
    
{"073542",
 "705141",
 "350721",
 "517031",
 "442304",
 "211140"}
Returns: 2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GameWithGraphAndTree

Dynamic Programming



Used in:

Member Single Round Match 474

Used as:

Division I Level Three

Writer:

K.A.D.R

Testers:

Rustyoldman , ivan_metelsky , mohamedafattah , it4.kp , maksay

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10800

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14185&pm=10800

Problem Statement

    

Little Dazdraperma likes graphs a lot. Recently she invented a new game for one person with graphs. Given a connected undirected graph with N vertices and a tree with N nodes (see the notes for definitions of all unclear terms from graph theory), she tries to place that tree on the graph in the following way:

  • Each node of the tree is put into correspondence with a vertex of the graph. Each node then corresponds to one vertex and each vertex corresponds to one node.
  • If there is an edge between two nodes of the tree then there must be an edge between the corresponding vertices in the graph.
Now Dazdraperma wonders how many ways are there to do such placement. Two placements are considered equal if each node of the tree corresponds to the same vertex of the graph in both placements. Return this number modulo 1000000007.



The graph will be represented as String[] graph where j-th character in i-th element will be 'Y' if there is an edge between vertices i and j and 'N' otherwise. The tree will be given in the same way in String[] tree.
 

Definition

    
Class:GameWithGraphAndTree
Method:calc
Parameters:String[], String[]
Returns:int
Method signature:int calc(String[] graph, String[] tree)
(be sure your method is public)
    
 

Notes

-For the purpose of this problem, an undirected graph can be treated as a set of vertices and a set of edges, where each edge establishes a bidirectional connection between two different vertices.
-A path between two different vertices A and B in a graph G is a sequence of 2 or more vertices v[0] = A, v[1], ..., v[L-1] = B, such that there's an edge in G between each two adjacent vertices in this sequence.
-A graph G is connected if there's a path between each two different vertices of G.
-A graph G is a tree if it is connected and contains exactly V-1 edges, where V is the total number of vertices in G.
 

Constraints

-graph will contain between 1 and 14 elements, inclusive.
-tree will contain the same number of elements as graph.
-Each element of graph will contain the same number of characters as the number of elements in graph.
-Each element of tree will contain the same number of characters as the number of elements in tree.
-Each character in each element of graph will be either 'Y' or 'N'.
-Each character in each element of tree will be either 'Y' or 'N'.
-For each i, i-th character of i-th element in both graph and tree will be equal to 'N'.
-For each i and j, j-th character of i-th element in graph will be equal to i-th character of j-th element.
-For each i and j, j-th character of i-th element in tree will be equal to i-th character of j-th element.
-graph will represent a connected graph.
-tree will represent a tree.
 

Examples

0)
    
{"NYN",
 "YNY",
 "NYN"}
{"NYY",
 "YNN",
 "YNN"}
Returns: 2
Vertex 1 of the graph must correspond to node 0 of the tree. There remain 2 possible ways to map vertices 0 and 2 of the graph.
1)
    
{"NYNNN",
 "YNYYY",
 "NYNYY",
 "NYYNY",
 "NYYYN"}
{"NYNNN", 
 "YNYNN",
 "NYNYN",
 "NNYNY",
 "NNNYN"}
Returns: 12
In this case vertex 0 of the graph can correspond only to nodes 0 and 4 of the tree. If it corresponds to 0, vertex 1 of the graph must correspond to node 1 of the tree. All other vertices can be mapped in any way, so there are 3! possible mappings. There are also 3! mappings when vertex 0 of the graph corresponds to node 4 of the tree. The total number of mappings is 2*3!=12.
2)
    
{"NYNNNY",
 "YNYNNN",
 "NYNYNN",
 "NNYNYN", 
 "NNNYNY",
 "YNNNYN"}
{"NYNNYN",
 "YNNYNY",
 "NNNNYN",
 "NYNNNN",
 "YNYNNN",
 "NYNNNN"}
Returns: 0
There are no possible mappings in this test case.
3)
    
{"NYNNYN",
 "YNNYNY",
 "NNNNYN",
 "NYNNNN",
 "YNYNNN",
 "NYNNNN"}
{"NNNYYN", 
 "NNYNNN",
 "NYNNYY", 
 "YNNNNN",
 "YNYNNN",
 "NNYNNN"}
Returns: 2
The graph can also be a tree.
4)
    
{"NYNNNYNNY",
 "YNNNNNNYN",
 "NNNNYYNYY",
 "NNNNNYNNY",
 "NNYNNNYNY",
 "YNYYNNNYN",
 "NNNNYNNYN",
 "NYYNNYYNN",
 "YNYYYNNNN"}
{"NNYNNNYYN",
 "NNNNYNNNN",
 "YNNNNNNNN",
 "NNNNNNYNN",
 "NYNNNNNYY",
 "NNNNNNNNY",
 "YNNYNNNNN",
 "YNNNYNNNN",
 "NNNNYYNNN"}
Returns: 90

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SubAnagrams

Dynamic Programming



Used in:

SRM 476

Used as:

Division II Level Three

Writer:

gojira_tc

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10798

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14186&pm=10798

Problem Statement

    A string X is an anagram of string Y if X can be obtained by arranging all characters of Y in some order, without removing any characters and without adding new characters. For example, each of the strings "baba", "abab", "aabb" and "abba" is an anagram of "aabb", and strings "aaab", "aab" and "aabc" are not anagrams of "aabb".



A string X is a subsequence of string Y if X can be obtained by removing some characters (possibly none) from Y and preserving the order of the remaining characters. For example, each of the strings "ac", "abd", "abcd" is a subsequence of "abcd", and strings "ca", "abb" and "abcde" are not subsequences of "abcd".



A string X is called a subanagram of Y if there exists a string Z such that X is an anagram of Z and Z is a subsequence of Y.



Manao is a big fan of subanagrams and he tries to find them everywhere. This time, he works on splitting strings into several parts in such a way that each of the parts (except the last one) is a subanagram of the following part. Formally, for a given string X, Manao wants to split it into several non-empty strings S1, S2, ..., Sn such that their concatenation S1 + S2 + ... + Sn equals X and each string Si (0 < i < n) is a subanagram of string Si+1.



You're given a String[] suppliedWord. Concatenate all its elements in the order they are given to obtain a single string X. Return the maximum number of parts into which Manao can split X so that the condition from the previous paragraph is satisfied.
 

Definition

    
Class:SubAnagrams
Method:maximumParts
Parameters:String[]
Returns:int
Method signature:int maximumParts(String[] suppliedWord)
(be sure your method is public)
    
 

Constraints

-suppliedWord will contain between 1 and 10 elements, inclusive.
-Each element of suppliedWord will contain between 1 and 50 characters, inclusive.
-suppliedWord will consist of uppercase letters ('A'-'Z') only.
 

Examples

0)
    
{"ABABAB"}
Returns: 3
Manao can split the given string in three "AB"-s.
1)
    
{"AAXAAAABX"}
Returns: 4
One of the possible ways to split "AAXAAAABX" into 4 parts is "A"+"A"+"XA"+"AAABX". "XA" is the anagram of "AX", a subsequence of "AAABX".
2)
    
{"ABCDEFGHIJKL"}
Returns: 1
This word is not splittable.
3)
    
{"ABBAB","B","BBX","Z"}
Returns: 2
Don't forget to concatenate the given strings.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GreenWarfare

Graph Theory



Used in:

Member SRM 465

Used as:

Division I Level Two

Writer:

vexorian

Testers:

timmac , ivan_metelsky , gojira_tc , boba5551 , keshav_57

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10792

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14182&pm=10792

Problem Statement

    The celebrated general Archibald Waving took charge of the fourth army in the occidental front. After losing the first three armies, Waving has become obsessed with efficient energy consumption. He has thus started innovating in what he calls "green warfare". He will use his newly acquired philosophy in an attempt to win the final battle of the occidental front. The development of death rays has been useful for Waving's side, but the plutonium required to shoot is scarce. The enemy side has bases and energy plants of its own and thus Waving has decided to take the initiative and destroy the enemy's forces once and for all, but using as little energy as possible.



The general has assigned you to determine how to accomplish this feat. Your main objective is to neutralize each of the enemy bases. A base is considered neutralized either if it was destroyed by a death ray or if all the energy plants supplying to it have been destroyed. There are a number of death ray canons that you can use and each canon may shoot multiple targets if necessary but can only destroy a single target with each shoot. The positions of the canons are given by two int[]s: canonX and canonY where the i-th canon is located at the point (canonX[i],canonY[i]). You can make each canon shoot a certain target at any distance but the energy required per target is equal to: d*d gigajoules where d is the euclidean distance between the target and the canon. The bases' positions are described by int[]s baseX and baseY where the i-th base is located at the point (baseX[i],baseY[i]), and the energy plants' locations are described by int[]s plantX and plantY where the i-th energy plant is located at the point (plantX[i],plantY[i]). An energy plant supplies energy to an enemy base if and only if the euclidean distance between them is less than or equal to energySupplyRadius. Return the minimum amount of energy required (in gigajoules), to neutralize all enemy bases.
 

Definition

    
Class:GreenWarfare
Method:minimumEnergyCost
Parameters:int[], int[], int[], int[], int[], int[], int
Returns:int
Method signature:int minimumEnergyCost(int[] canonX, int[] canonY, int[] baseX, int[] baseY, int[] plantX, int[] plantY, int energySupplyRadius)
(be sure your method is public)
    
 

Constraints

-baseX, baseY, canonX, canonY, plantX and plantY will each contain between 1 and 50 elements, inclusive.
-baseX and baseY will contain the same number of elements.
-canonX and canonY will contain the same number of elements.
-plantX and plantY will contain the same number of elements.
-The position given for each canon, base and energy plant will be unique.
-Each element in baseX, baseY, canonX, canonY, plantX and plantY will be between -500 and 500, inclusive.
-energySupplyRadius will be between 1 and 2000, inclusive.
-Every base will be within energySupplyRadius distance units to at least one energy plant.
 

Examples

0)
    
{ 0 }
{ 0 }
{1,2,3}
{0,0,0}
{3}
{3}
4
Returns: 14
Use the canon to destroy each base individually, the costs are: 1, 4 and 9 gigajoules. The total cost is 14 gigajoules.
1)
    
{ 0 }
{ 0 }
{1,2,3}
{0,0,0}
{2}
{2}
4
Returns: 8
In this case, the distance between the energy plant and the canon is smaller and the new optimal strategy is to destroy the energy plant with a cost of 8 gigajoules.
2)
    
{3,6}
{3,6}
{1,2,3,4,5}
{5,4,2,3,1}
{1,2,5}
{1,2,5}
5
Returns: 12
Use the first canon to destroy the first two energy plants, use the second canon to destroy the remaining one.
3)
    
{0}
{0}
{-10,-10,10}
{10,-10,0}
{10,10,-10}
{10,-10,0}
10
Returns: 200
Destroy the base at (10,0) and the energy plant at (-10,0), 200 gigajoules are required in total.
4)
    
{0}
{0}
{3}
{3}
{1,2,3}
{0,0,0}
4
Returns: 14

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TimeTravellingTour

Dynamic Programming, Graph Theory



Used in:

SRM 492

Used as:

Division I Level Two

Writer:

dolphinigle

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10782

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14245&pm=10782

Problem Statement

    NOTE: This problem statement contains images that may not display properly if viewed outside of the applet.



There is a kingdom with N cities numbered 0 through N-1. Gogo wants to survey several cities in the kingdom. These cities are described in int[] cities containing M elements. He wishes to survey city cities[0], city cities[1], ..., city cities[M-1] in this exact order (i.e., before surveying city cities[i], he must have finished surveying cities cities[0], ..., cities[i-1] in this order). He starts at city 0 and can end at any city. He may only survey a city when he's inside the city. There are several bidirectional roads, each connecting two different cities and costing some amount of money to traverse. Note that he may wish to survey the same city multiple times.



Gogo also has a time machine. He can use the time machine to go back in time, without affecting which cities he is considered to have already surveyed. For example, suppose he has visited cities A, B, C, D, and E, in that order, and is currently in city E. He can use the time machine to go back to city A, B, C, or D. Suppose he chooses to go back to city C. At that point, he can then go back further to city A or B, but he cannot use the time machine to go forward to city D or E. Note that if he had surveyed city E, going back in time will not change the fact that he is considered to have already surveyed city E.



You are given the roads in the String[] roads. Concatenate the elements of roads, in order, to get a single space-separated list of roads. Each road will be formatted "a,b,travelcost" (quotes for clarity), which means that the bidirectional road connects city a and city b, and costs travelcost to traverse.



He can use the time machine any number of times, and it costs nothing to use it. Return the minimum cost required to survey all cities from cities in the given order. Return -1 if it is impossible to survey them all.
 

Definition

    
Class:TimeTravellingTour
Method:determineCost
Parameters:int, int[], String[]
Returns:long
Method signature:long determineCost(int N, int[] cities, String[] roads)
(be sure your method is public)
    
 

Notes

-Surveying a city does not incur any cost.
 

Constraints

-N will be between 2 and 50, inclusive.
-cities will contain between 1 and 50 elements, inclusive.
-Each element of cities will be between 0 and N-1, inclusive.
-No two consecutive elements in cities will be identical.
-cities[0] will not be 0.
-roads will contain between 1 and 50 elements, inclusive.
-Each element of roads will contain between 1 and 50 characters, inclusive.
-Each character in roads will be '0'-'9', ' ', or ','.
-roads will be formatted as described in the problem statement without leading or trailing spaces.
-All integers in the concatenation of all the elements of roads in the order they are given will have no leading zeroes.
-In each road, a and b as described in the problem statement will be different and will each be between 0 and N-1, inclusive.
-In each road, travelcost as described in the problem statement will be between 1 and 10,000,000, inclusive.
-For each two different cities, there will be at most one road connecting them.
 

Examples

0)
    
5
{2,3,2,4}
{"0,2,4 0,1,2 2,1,2 1,3,3 4,0,4"}
Returns: 13


Travel from city 0 to city 1 to city 2. Survey city 2. Go back in time to city 1. Travel from city 1 to city 3. Survey city 3. Go back in time to city 1. Travel from city 1 to city 2. Survey city 2. Go back in time to city 0. Travel from city 0 to city 4. Survey city 4. The total cost is 2+2+3+2+4=13.
1)
    
3
{1,0,1}
{"0,2,1"," 2",",1,5"}
Returns: 12


Travel from city 0 to city 2 to city 1. Survey city 1. Go back in time to city 0. Survey city 0. Travel from city 0 to city 2 to city 1. Survey city 1.
2)
    
3
{2}
{"0,1,2"}
Returns: -1


It is not possible to reach city 2.
3)
    
6
{4, 1, 3, 2}
{"0,1,5 0,2,5 0,5,2 2,3,5 2,4,2 3,4,4 3,5,1"}
Returns: 19




Travel from city 0 to city 2 to city 4. Survey city 4. Travel from city 4 to city 3 to city 5 to city 0 to city 1. Survey city 1. Go back in time to city 3. Survey city 3. Go back in time to city 2. Survey city 2. The total cost is 5+2+4+1+2+5=19

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Gifts

Dynamic Programming, Graph Theory



Used in:

Member SRM 468

Used as:

Division II Level Three

Writer:

keshav_57

Testers:

Rustyoldman , ivan_metelsky , mohamedafattah , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10767

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14183&pm=10767

Problem Statement

    The king loves his queen a lot. The king wants to give a pleasant surprise to his queen and thus he wants to collect gifts for her.



You are given a String[] city which represents a rectangular grid where the j-th character in the i-th element of city is the description of the cell in row i and column j of the grid. Each cell can be of one of the following types:

  • '.' - Passable cell.
  • '#' - Unpassable cell.
  • 'K' - The initial position of the king.
  • 'Q' - The position of the queen.
  • 'G' - Cell with a gift.
Note that the cells in which the king, queen and gifts are present are also passable cells.



The king can move from one cell to another if and only if both the cells are passable cells and they share a common edge (diagonal moves are not allowed). It takes the king (g+1) time units to go from a passable cell to an adjacent passable cell when the king is carrying g gifts. If the cell contains a gift then the king may collect the gift (but he doesn't have to collect it). The king does not need any additional time to collect the gift.



The king starts his trip in his initial cell. He then moves in arbitrary horizontal and vertical steps through passable cells to collect some gifts (possibly zero) and finishes the trip in the cell of the queen. The total time spent for the trip must not exceed T time units because the queen eagerly awaits the king. Return the maximum number of gifts the king can collect for the queen during such a trip. You may assume that it's always possible for the king to finish the trip within T time units.
 

Definition

    
Class:Gifts
Method:maxGifts
Parameters:String[], int
Returns:int
Method signature:int maxGifts(String[] city, int T)
(be sure your method is public)
    
 

Notes

-The king can visit any cell multiple times during the trip.
 

Constraints

-city will contain between 1 and 50 elements, inclusive.
-Each element of city will contain between 1 and 50 characters, inclusive.
-All elements of city will have the same length.
-Each character in city will be '.', '#', 'K', 'Q' or 'G'.
-There will be exactly one 'K' character and one 'Q' character in city.
-The number of 'G' characters in city will be between 0 and 16, inclusive.
-T will be between 1 and 1000000000, inclusive.
 

Examples

0)
    
{"#######",
 "#K.G.Q#",
 "#######"}
6
Returns: 1
The king collects the gift and then goes to the queen. It takes him 2 time units to reach the gift and 4 time units to reach the queen after collecting the gift (since every move takes 2 time units after he has collected the gift). Hence, the king can collect 1 gift and reach the queen in 2 + 4 = 6 time units.
1)
    
{"#######",
 "#K.G.Q#",
 "#######"}
4
Returns: 0
The king does not have enough time to collect the gift, so he chooses not to collect the gift even though he passes through that cell.
2)
    
{"#######",
 "#K.Q.G#",
 "#######"}
6
Returns: 0
It will take the king 4 time units to reach the gift and collect it. Then another 4 time units to reach the queen after collecting the gift. But he does not have 4 + 4 = 8 time units. Hence, he goes to the queen without any gifts.
3)
    
{"#######",
 "#K.Q.G#",
 "#######"}
8
Returns: 1
Now the king has enough time to collect the gift and return to the queen.
4)
    
{"#######",
 "#K.QGG#",
 "#######"}
9
Returns: 2
The king collects the gift on the left when he visits that cell for the second time.
5)
    
{"#....G#", 
 "###G###", 
 "#K...Q#", 
 "###.###", 
 "#G..GG#"}
50
Returns: 4

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PythTriplets

Graph Theory, Simple Math



Used in:

SRM 477

Used as:

Division I Level Two

Writer:

keshav_57

Testers:

PabloGilberto , ivan_metelsky , mohamedafattah

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10766

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14157&pm=10766

Problem Statement

    The prince has just been introduced to primitive pythagorean triplets.

A primitive pythagorean triplet (a, b, c) is a triplet satisfying the following properties:

  • a, b and c are integers
  • a^2 + b^2 = c^2
  • The greatest common divisor of a and b is 1
The prince is not very fond of mathematics. The king is trying to make mathematics fun for his son (the prince). So, the king decides to make as many toys as possible which are triangular in shape having sides (a, b, c) where (a, b, c) form a primitive pythogorean triplet. The wooden framework of the two shorter legs of the toy give the toy its shape and prevent it from breaking, hence each toy with sides of length (a, b, c) must have one wooden stick of length a and one of length b. The third side of length c is not made of wood, and therefore the king does not need a wooden stick for it.



You are given a String[] stick. Concatenate the elements of stick to get a single-space separated list of the lengths of available sticks. The king is a very loving father and would like to make the toys with his own hands. However, he is not skilled enough to cut the sticks, so he must use them in the sizes they are available. Return the maximum possible number of toys the king can make using these sticks.

 

Definition

    
Class:PythTriplets
Method:findMax
Parameters:String[]
Returns:int
Method signature:int findMax(String[] stick)
(be sure your method is public)
    
 

Notes

-An integer may be listed multiple times in the String formed by the concatenation of stick . If an integer n is listed k times, then the king has exactly k sticks of length n available with him.
 

Constraints

-stick will contain between 1 and 50 elements, inclusive.
-Each element of stick will contain between 1 and 50 characters, inclusive.
-When concatenated, stick will represent a single-space separated list of N integers, where N is between 1 and 200 inclusive.
-Each listed integer will be between 1 and 999999, inclusive.
-Listed integers will not have leading zeroes.
 

Examples

0)
    
{"3 4 4 3 11 5 12 9 4"}
Returns: 3
(3, 4, 5) and (5, 12, 13) are primitive pythagorean triplets. Hence, there are three disjoint pairs (a, b) - (3, 4), (3, 4) and (5, 12).
1)
    
{"20 21 3021 220"}
Returns: 2
Possible pairs (a, b) are (20, 21), (21, 220) and (220, 3021). The maximum number of disjoint pairs is 2. Namely, (20, 21) and (220, 3021).
2)
    
{"28 19", "5 1035 21412 37995"}
Returns: 2
Make sure you concatenate the elements of stick.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

T9

Simulation, String Manipulation



Used in:

Member SRM 468

Used as:

Division I Level One , Division II Level Two

Writer:

keshav_57

Testers:

Rustyoldman , ivan_metelsky , mohamedafattah , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10762

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14183&pm=10762

Problem Statement

    The old fashioned king does not know how to SMS and thus he is having problems sending messages to the queen. In particular, he is having a problem with a feature called T9.



In T9, the set of alphabets are partitioned into 9 sets, where the i-th set of characters (1-based) denotes the possible characters that may be typed by pressing digit i. For this problem, we will use strings to denote a set of characters. On a standard modern cell phone, the following partition is used

	{"", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
For the partition above, pressing 2 may output 'a', 'b' or 'c'; pressing 3 may output 'd', 'e' or 'f'; and so on. Pressing 223 can give you various outputs of the form "(abc)(abc)(def)" where (XYZ) means that the letter can be either X or Y or Z. For example, a few possible outputs are "ace", "bad" and "bbe".



However, not all possible outputs are dictionary words (like "bbe" is not a dictionary word), and thus these outputs do not make sense. The cell phone considers only those outputs which correspond to dictionary words. Suppose that there are only two possible dictionary words from "(abc)(abc)(def)" - namely, "ace" and "bad". Then, the keystrokes 223 gives the output "ace", and the keystrokes 223# gives the output "bad". In general if a certain number (like 223) corresponds to multiple dictionary words, then the number followed by n hashes ('#') is used to type the n-th dictionary word (0-based) from the lexographically sorted list of dictionary words corresponding to the number. Sometimes the number of hashes typed can be quite large. Hence, we have a special character star ('*') which is equivalent to 5 contiguous hashes. The digit 0 is used to type a space.



The king needs to type a text using T9. The text is a String that consists of lowercase letters ('a'-'z') and space characters (' '). A word is a maximal contiguous substring of the text that contains only lowercase letters ('a'-'z'). The only way the king can type a word is by first pressing a non-empty sequence of digits ('1'-'9') followed by a (possibly emtpy) sequence of characters '#' and/or '*'. You will be given a String[] part whose i-th element (1-based) is the set of alphabets which correspond to the digit i. You will also be given a String[] dict that represents a set of all dictionary words, where each element is a single word. Finally, you will be given a String[] keystr. Concatenate the elements of keystr in the same order as they are given to obtain a String. This String represents the keystrokes pressed by the king. To help the king, return the text that will result when the given keystrokes are pressed. You may assume that the given keystrokes are valid, i.e. each maximal contiguous substring that doesn't contain '0' characters starts from non-empty sequence of digits ('1'-'9') and then is optionally continued with a sequence of '#' and/or '*' characters. You may also assume that each such substring corresponds to a word from dict.
 

Definition

    
Class:T9
Method:message
Parameters:String[], String[], String[]
Returns:String
Method signature:String message(String[] part, String[] dict, String[] keystr)
(be sure your method is public)
    
 

Notes

-A substring of a String is called maximal with respect to some property if it can't be extended to the left or to the right while maintaining the property.
-A string A is lexicographically less than another string B of the same length if there exists a position i such that each character of A before the i-th position is equal to the character at the corresponding position in B, and A[i] is less than B[i].
-For the purpose of this problem, a partition of alphabets into 9 sets may contain any number of empty sets.
 

Constraints

-part will represent a valid partition of the 26 english alphabets into 9 sets, i.e. it will consist of exactly 9 elements and every letter from 'a' to 'z' will appear exactly once in exactly one of the elements of part.
-dict will contain between 1 and 50 elements, inclusive.
-Each element of dict will contain between 1 and 50 characters, inclusive.
-Each character in dict will be a lowercase letter 'a'-'z'.
-All elements of dict will be distinct.
-keystr will contain between 1 and 50 elements, inclusive.
-Each element of keystr will contain between 1 and 50 characters, inclusive.
-Each character in keystr will be one of '0'-'9', '#', '*'.
-The length of the resulting text will be between 1 and 1000, inclusive.
-The String obtained by concatenating the elements of keystr will represent a valid sequence of keystrokes (as explained in the statement).
 

Examples

0)
    
{"", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
{"bad"}
{"2230223"}
Returns: "bad bad"
1)
    
{"", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
{"the", "tie"}
{"0843#000843#000"}
Returns: " tie   tie   "
There may be leading, trailing and contiguous spaces.
2)
    
{"", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
{"bad", "ace", "aad", "aae", "aaf", "acf", "acd", "the", "tie"}
{"223#02", "23*#00843#0"}
Returns: "aae bad  tie "
Don't forget to concatenate the elements of keystr. Also, "*" is equivalent to "#####".
3)
    
{"", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
{"the", "tie", "bad", "ace", "aad", "aae", "aaf", "acf", "acd"}
{"84300223#02", "23#*"}
Returns: "the  aae bad"
'*' may also appear after the '#'. All that matters is, it is equivalent to "#####".
4)
    
{"", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
{"bad", "ace", "aad", "aae", "tie", "aaf", "acf", "acd", "the"}
{"223#02", "23######"}
Returns: "aae bad"
The king may use '*'. But it is not necessary that he uses it everytime he is allowed to use it.
5)
    
{"", "rq", "lde", "yoauz", "cbfgn", "tjkpx", "wvs", "ih", "m"}
{"xktgmfmoqlmivm", 
 "hmthr", 
 "tpjgmnmaremiwm", 
 "tpjcmnmyrlmhvm", 
 "xkpnmgmzqdmhsm", 
 "wqopvvmiig", 
 "melbcbqeeg", 
 "jkxnmbmardmhwm", 
 "kpxnmcmyqlmism", 
 "wrztvsmhhf", 
 "srztssmiic", 
 "pxtgmfmyrdmhwm", 
 "vqoxswmiin", 
 "wryksvmihb", 
 "ptjfmbmoremhvm"}
{"00", 
 "7246779885##00000089682000007246779885##0000724677", 
 "9885#000089682000093355523350066659594239879###000"}
Returns: 
"  wqopvvmiig      hmthr     wqopvvmiig    vqoxswmiin    hmthr    melbcbqeeg  pxtgmfmyrdmhwm   "

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ActivateGame

Graph Theory, Greedy



Used in:

SRM 470

Used as:

Division II Level Three

Writer:

dolphinigle

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10750

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14153&pm=10750

Problem Statement

    ActivateGame is played on a rectangular grid with N rows and M columns. The rows are numbered 0 to N-1 from top to bottom, and the columns are numbered 0 to M-1 from left to right. A number is assigned to each cell.



The game is played as follows. Initially, only the top-left cell (row 0, column 0) is activated, and your score is zero. Then, on each turn, you choose one activated cell and one non-activated cell which is vertically or horizontally adjacent to that cell. The absolute difference between the numbers assigned to those two cells is added to your score, and the non-activated cell becomes activated. This is repeated until all the cells have been activated.



You are given a String[] grid. The j-th character of the i-th element of grid represents the number assigned to the cell at row i, column j. Characters are mapped to numbers as follows:
  • '0' - '9' corresponds to 0 - 9
  • 'a' - 'z' corresponds to 10 - 35
  • 'A' - 'Z' corresponds to 36 - 61
Return the maximum possible score you can achieve.
 

Definition

    
Class:ActivateGame
Method:findMaxScore
Parameters:String[]
Returns:int
Method signature:int findMaxScore(String[] grid)
(be sure your method is public)
    
 

Constraints

-grid will contain between 1 and 50 elements, inclusive.
-Each element of grid will contain between 1 and 50 characters, inclusive.
-Each element of grid will contain the same number of characters.
-grid will contain at least two characters.
-Each character in grid will be '0'-'9', 'a'-'z', or 'A'-'Z'.
 

Examples

0)
    
{"05",
 "aB"}
Returns: 69
Initially only the cell containing '0' is activated. Use the following sequence of moves to maximize your score:
  1. Choose the activated cell containing '0' and the adjacent non-activated cell containing 'a' (which represents the number 10). Their absolute difference, 10, is added to your score, and the cell containing 'a' becomes activated.
  2. Choose the activated cell containing 'a' and the adjacent non-activated cell containing 'B' (which represents the number 37). Their absolute difference is 27.
  3. Choose the activated cell containing 'B' and the adjacent non-activated cell containing '5' (which represents the number 5). Their absolute difference is 32.
Your total score is 10 + 27 + 32 = 69.
1)
    
{"03",
 "21"}
Returns: 7
One possible solution is to choose cells in the following order:
  1. 0 and 3
  2. 0 and 2
  3. 3 and 1
2)
    
{"John",
 "Brus",
 "Gogo"}
Returns: 118
3)
    
{"AAA",
 "AAA",
 "AAA"}
Returns: 0

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ColorfulMazeTwo

Dynamic Programming, Graph Theory



Used in:

SRM 464

Used as:

Division II Level Three

Writer:

lyrically

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10742

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14149&pm=10742

Problem Statement

    You have just entered the Colorful Maze. You are given the layout of the maze in the String[] maze, where the j-th character of the i-th element is the cell at row i, column j. The following types of cells exist in the maze:
  • '#' - Wall. You cannot enter these cells.
  • '.' - Empty cell. You can walk freely into these cells.
  • 'A'-'G' - Empty cell with a colored floor. Each of 'A'-'G' represents a different color. You can walk into these cells.
  • '$' - Entrance. This is the cell in which you start.
  • '!' - Exit. This is the cell you must reach to finish the maze.


Colored floors with certain colors are dangerous, but you don't know upfront which colors are dangerous. You only know the probability of each color being dangerous. You are given a int[] trap, where the first element is the percent probability of color 'A' being dangerous, the second element is the percent probability of color 'B' being dangerous, and so on. When you step into a cell with a dangerous color, you get damaged by a trap.



When you're inside the maze, you can only move in the four cardinal directions. You cannot move diagonally. Return the probability that you can finish the maze without getting damaged, assuming that you walk according to a strategy that maximizes this probability. See examples for further clarification.
 

Definition

    
Class:ColorfulMazeTwo
Method:getProbability
Parameters:String[], int[]
Returns:double
Method signature:double getProbability(String[] maze, int[] trap)
(be sure your method is public)
    
 

Notes

-The returned value must have an absolute or relative error less than 1e-9.
 

Constraints

-maze will contain between 1 and 50 elements, inclusive.
-Each element of maze will contain between 1 and 50 characters, inclusive.
-Each element of maze will contain the same number of characters.
-Each character in maze will be one of '#', '.', 'A', 'B', 'C', 'D', 'E', 'F', 'G', '$', and '!'.
-maze will contain exactly one '$' and exactly one '!'.
-trap will contain exactly 7 elements.
-Each element of trap will be between 0 and 100, inclusive.
 

Examples

0)
    
{ ".$.",
  "A#B",
  "A#B",
  ".!." }
{ 50, 50, 0, 0, 0, 0, 0 }
Returns: 0.5
First, go left one cell, and then down one cell into the 'A'. One of two things might happen with equal probability:
  • You get damaged. You fail to finish the maze.
  • You do not get damaged. This means all cells with color 'A' are safe, so you can continue through the 'A' zone and get to the exit.
The probability of reaching the exit is 0 (the first case) + 0.5 (the second case) = 0.5.

The probability is the same if you go through the 'B' zone.
1)
    
{ ".$.",
  "A#B",
  "A#B",
  ".!." }
{ 50, 40, 0, 0, 0, 0, 0 }
Returns: 0.6
As 'B' is safer than it was in the previous example, it is better to go through the 'B' zone.
2)
    
{ "$A#",
  ".#.",
  "#B!" }
{ 10, 10, 10, 10, 10, 10, 10 }
Returns: 0.0
No matter how you walk, you cannot reach the exit, so you should return 0.
3)
    
{ "$A..",
  "##.A",
  "..B!" }
{ 50, 50, 0, 0, 0, 0, 0 }
Returns: 0.5
4)
    
{ "$C..",
  "##.A",
  "..B!" }
{ 50, 50, 100, 0, 0, 0, 0 }
Returns: 0.0
5)
    
{ ".$.D.E.F.G.!." }
{ 10, 20, 30, 40, 50, 60, 70 }
Returns: 0.036000000000000004

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ColorfulMaze

Dynamic Programming, Graph Theory



Used in:

SRM 464

Used as:

Division I Level Three

Writer:

lyrically

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10741

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14149&pm=10741

Problem Statement

    You have just entered the Colorful Maze. You are given the layout of the maze in the String[] maze, where the j-th character of the i-th element is the cell at row i, column j. The following types of cells exist in the maze:
  • '#' - Wall. You cannot enter these cells.
  • '.' - Empty cell. You can walk freely into these cells.
  • 'A'-'G' - Empty cell with a colored floor. Each of 'A'-'G' represents a different color. You can walk into these cells.
  • '$' - Entrance. This is the cell in which you start.
  • '!' - Exit. This is the cell you must reach to finish the maze.


Colored floors with certain colors are dangerous, but you don't know upfront which colors are dangerous. You only know the probability of each color being dangerous. You are given a int[] trap, where the first element is the percent probability of color 'A' being dangerous, the second element is the percent probability of color 'B' being dangerous, and so on. When you step into a cell with a dangerous color, you get damaged by a trap. If you get damaged twice, you die.



When you're inside the maze, you can only move in the four cardinal directions. You cannot move diagonally. Return the probability that you can finish the maze without dying, assuming that you walk according to a strategy that maximizes this probability. See examples for further clarification.
 

Definition

    
Class:ColorfulMaze
Method:getProbability
Parameters:String[], int[]
Returns:double
Method signature:double getProbability(String[] maze, int[] trap)
(be sure your method is public)
    
 

Notes

-The returned value must have an absolute or relative error less than 1e-9.
 

Constraints

-maze will contain between 1 and 50 elements, inclusive.
-Each element of maze will contain between 1 and 50 characters, inclusive.
-Each element of maze will contain the same number of characters.
-Each character in maze will be one of '#', '.', 'A', 'B', 'C', 'D', 'E', 'F', 'G', '$', and '!'.
-maze will contain exactly one '$' and exactly one '!'.
-trap will contain exactly 7 elements.
-Each element of trap will be between 0 and 100, inclusive.
 

Examples

0)
    
{ ".$.",
  "A#B",
  "A#B",
  ".!." }
{ 50, 40, 0, 0, 0, 0, 0 }
Returns: 0.8
First, go left one cell, and then down one cell into the 'A'. One of two things might happen with equal probability:
  • You get damaged. This means all cells with color 'A' are dangerous, so you should go back and try going through the 'B' zone instead (which might also be dangerous).
  • You do not get damaged. This means all cells with color 'A' are safe, so you can continue through the 'A' zone and get to the exit.
The probability of reaching the exit is 0.5 * 0.6 (the first case) + 0.5 (the second case) = 0.8.

The probability is the same if you try 'B' first.
1)
    
{ ".$.",
  "A#B",
  "A#C",
  ".!." }
{ 20, 70, 40, 0, 0, 0, 0 }
Returns: 0.86
If you try 'A' first:
  • You get damaged. You should go back and try going through the 'B' and 'C' zone.
  • You do not get damaged. You can continue through the 'A' zone.
The probability is 0.2 * 0.3 * 0.6 (the first case) + 0.8 (the second case) = 0.836.

If you try 'B' first:
  • You get damaged. You can choose either going back to try 'A' or going ahead to try 'C'. Going through the 'A' zone is safer.
  • You do not get damaged. Whether 'C' is dangerous or not, you can go through 'C' and get to the exit.
The probability is 0.7 * 0.8 (the first case) + 0.3 (the second case) = 0.86.

You see that trying 'B' first is a better choice.
2)
    
{ "$A#",
  ".#.",
  "#B!" }
{ 10, 10, 10, 10, 10, 10, 10 }
Returns: 0.0
No matter how you walk, you cannot reach the exit, so you should return 0.
3)
    
{ "$A..",
  "##.A",
  "..B!" }
{ 50, 50, 0, 0, 0, 0, 0 }
Returns: 0.75
4)
    
{ "$C..",
  "##.A",
  "..B!" }
{ 50, 50, 100, 0, 0, 0, 0 }
Returns: 0.5
5)
    
{ ".$.D.E.F.G.!." }
{ 10, 20, 30, 40, 50, 60, 70 }
Returns: 0.23400000000000004
6)
    
{ "CC...AA",
  "C##.##A",
  "!.E.E.$",
  "D##.##B",
  "DD...BB" }
{ 90, 90, 25, 50, 75, 0, 0 }
Returns: 0.8125

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ColorfulDecoration

Graph Theory



Used in:

SRM 464

Used as:

Division I Level Two

Writer:

lyrically

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10739

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14149&pm=10739

Problem Statement

    You are going to decorate a very large white board with square sheets of colored paper. Each sheet of paper can be of any non-zero size. You have chosen N colors, numbered 0 to N - 1, and you will use exactly one sheet of each color. You are given four int[]s, xa, ya, xb, and yb, each containing exactly N elements. The sheet of paper with color i must be placed so that its center is at either (xa[i], ya[i]) or (xb[i], yb[i]). All sides of the paper must be parallel to the coordinate axes, and no two sheets of paper can overlap each other (Two squares overlap if their intersection has a non-zero area).



Return the maximum possible size of the smallest of the N sheets of paper. The size of a square sheet of paper is its side length. If you cannot place all N sheets, then return 0 instead.
 

Definition

    
Class:ColorfulDecoration
Method:getMaximum
Parameters:int[], int[], int[], int[]
Returns:int
Method signature:int getMaximum(int[] xa, int[] ya, int[] xb, int[] yb)
(be sure your method is public)
    
 

Notes

-It can be proved that the answer is always an integer.
 

Constraints

-xa will contain between 2 and 50 elements, inclusive.
-xa, ya, xb, and yb will contain the same number of elements.
-Each element of xa, ya, xb, and yb will be between 0 and 1,000,000,000, inclusive.
 

Examples

0)
    
{ 10,  0,  7 }
{  0, 19,  6 }
{ 20, 10, 25 }
{ 20, 35, 25 }
Returns: 19


In the picture above, the numbers represent the candidates for the center of each color.

Choose (10, 0) for color 0, (0, 19) for color 1, and (25, 25) for color 2. The paper with color 2 could be larger, but the size of the smallest sheet cannot exceed 19.
1)
    
{ 464, 20 }
{ 464, 10 }
{ 464,  3 }
{ 464, 16 }
Returns: 461
(xa[i], ya[i]) and (xb[i], yb[i]) might be the same.
2)
    
{ 0, 0, 1, 1 }
{ 0, 0, 1, 1 }
{ 1, 1, 0, 0 }
{ 1, 1, 0, 0 }
Returns: 0
No matter how we choose to place the squares, at least two of them will have the same center. This means we cannot place four sheets of non-zero size without overlapping, so we return 0.
3)
    
{ 0, 3, 0, 5, 6 }
{ 1, 6, 0, 8, 5 }
{ 6, 1, 7, 4, 7 }
{ 5, 9, 2, 8, 9 }
Returns: 3
4)
    
{ 1000000000, 0 }
{ 0, 1000000000 }
{ 0, 1000000000 }
{ 0, 1000000000 }
Returns: 1000000000

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheContest

Graph Theory



Used in:

SRM 459

Used as:

Division I Level Three

Writer:

gojira_tc

Testers:

PabloGilberto , legakis , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10738

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14145&pm=10738

Problem Statement

    A contest is held between two teams of fighters. The first team is comprised of N persons and the second is comprised of M persons. In the course of the contest, each fighter of the first team will confront each fighter of the second team once. To make the contest more entertaining and less protracted, the organizers divided it into several rounds. In each of the rounds, several fights occur simultaneously. Therefore, a fighter may only participate in one fight per round.



The contest must be divided into the least number of rounds. One can easily see that this number is the maximum between N and M. Now the exact schedule of fights must be determined. Return a String[] containing exactly N elements. Each element of the return must contain exactly M characters from the set {'1'-'9', 'A'-'Z', 'a'-'o'}. Letters 'A'-'Z' stand for numbers 10-35 and 'a'-'o' stand for numbers 36-50. The j-th character of element i corresponds to the number of the round in which fighter i of the first team encounters fighter j of the second team. If there are several possible schedules, return the one with the lexicographically least first element. If there still are multiple choices, choose the schedule with the lexicographically least second element, and so on.
 

Definition

    
Class:TheContest
Method:getSchedule
Parameters:int, int
Returns:String[]
Method signature:String[] getSchedule(int N, int M)
(be sure your method is public)
    
 

Notes

-A string A is lexicographically less than another string B of the same length if there exists a position i such that each character of A before the i-th position is equal to the character at the corresponding position in B, and A[i] is less than B[i]. When comparing the characters, refer to the following list of characters in ascending order: '1', '2', ..., '9', 'A', 'B', ..., 'Z', 'a', 'b', ..., 'o'.
 

Constraints

-N will be between 1 and 50, inclusive.
-M will be between 1 and 50, inclusive.
 

Examples

0)
    
3
3
Returns: {"123", "231", "312" }
There are three persons on each team, so the whole contest is divided into three rounds. If we denote the i-th person of the first team as Ai and the j-th person of the second team as Bj, the fights schedule for each of the rounds is:

Round 1: A1-B1, A2-B3, A3-B2

Round 2: A1-B2, A2-B1, A3-B3

Round 3: A1-B3, A2-B2, A3-B1

1)
    
4
4
Returns: {"1234", "2143", "3412", "4321" }
This time, both teams comprise of four persons, so the contest takes 4 rounds to finish.

Round 1: A1-B1, A2-B2, A3-B3, A4-B4

Round 2: A1-B2, A2-B1, A3-B4, A4-B3

Round 3: A1-B3, A2-B4, A3-B1, A4-B2

Round 4: A1-B4, A2-B3, A3-B2, A4-B1

2)
    
4
6
Returns: {"123456", "214365", "345612", "436521" }
The competition now is held in 6 rounds. Note that since the teams are of unequal size, two of the second team's fighters are taking rest in each of the rounds.

Round 1: A1-B1, A2-B2, A3-B5, A4-B6

Round 2: A1-B2, A2-B1, A3-B6, A4-B5

Round 3: A1-B3, A2-B4, A3-B1, A4-B2

Round 4: A1-B4, A2-B3, A3-B2, A4-B1

Round 5: A1-B5, A2-B6, A3-B3, A4-B4

Round 6: A1-B6, A2-B5, A3-B4, A4-B3

3)
    
5
3
Returns: {"123", "214", "345", "451", "532" }
4)
    
28
40
Returns: 
{"123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcde",
"21436587A9CBEDGFIHKJMLONQPSRUTWVYXaZcbed",
"34127856BC9AFGDEJKHINOLMRSPQVWTUZaXYdebc",
"43218765CBA9GFEDKJIHONMLSRQPWVUTaZYXedcb",
"56781234DEFG9ABCLMNOHIJKTUVWPQRSbcdeXYZa",
"65872143EDGFA9CBMLONIHKJUTWVQPSRcbedYXaZ",
"78563412FGDEBC9ANOLMJKHIVWTURSPQdebcZaXY",
"87654321GFEDCBA9ONMLKJIHWVUTSRQPedcbaZYX",
"9ABCDEFG12345678PQRSTUVWXYZabcdeHIJKLMNO",
"A9CBEDGF21436587QPSRUTWVYXaZcbedIHKJMLON",
"BC9AFGDE34127856RSPQVWTUZaXYdebcJKHINOLM",
"CBA9GFED43218765SRQPWVUTaZYXedcbKJIHONML",
"DEFG9ABC56781234TUVWPQRSbcdeXYZaLMNOHIJK",
"EDGFA9CB65872143UTWVQPSRcbedYXaZMLONIHKJ",
"FGDEBC9A78563412VWTURSPQdebcZaXYNOLMJKHI",
"GFEDCBA987654321WVUTSRQPedcbaZYXONMLKJIH",
"HIJKLMNOPQRSTUVWXYZabcde123456789ABCDEFG",
"IHKJMLONQPSRUTWVYXaZcbed21436587A9CBEDGF",
"JKHINOLMRSPQVWTUZaXYdebc34127856BC9AFGDE",
"KJIHONMLSRQPWVUTaZYXedcb43218765CBA9GFED",
"LMNOHIJKTUVWPQRSbcdeXYZa56781234DEFG9ABC",
"MLONIHKJUTWVQPSRcbedYXaZ65872143EDGFA9CB",
"NOLMJKHIVWTURSPQdebcZaXY78563412FGDEBC9A",
"ONMLKJIHWVUTSRQPedcbaZYX87654321GFEDCBA9",
"PQRSTUVWXYZabcde9ABCDEFGHIJKLMNO12345678",
"QPSRUTWVYXaZcbedA9CBEDGFIHKJMLON21436587",
"RSPQVWTUZaXYdebcBC9AFGDEJKHINOLM34127856",
"SRQPWVUTaZYXedcbCBA9GFEDKJIHONML43218765" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BuildingRoads

Dynamic Programming, Graph Theory



Used in:

SRM 470

Used as:

Division I Level Three

Writer:

dolphinigle

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10737

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14153&pm=10737

Problem Statement

    You are given the map of a country which is divided into a rectangular grid of cells. The country contains several cities, each of which occupies a single cell. Your goal is to connect certain pairs of cities with direct roads. However, there are several large rocks which might get in your way. Each rock potentially spans multiple cells, and costs some amount of money to destroy. You want to build your roads while spending as little money as possible destroying rocks.



You are given the map in the String[] field. The j-th character of the i-th element of field represents the cell at row i, column j. Each cell is one of the following:
  • '.' - Empty space.
  • '!', '@', '#', or '$' - A city. For each of these characters, there can be either 0 or 2 cities denoted by it.
  • 'a'-'z', 'A'-'Z', or '0'-'9' - A cell which is occupied entirely by a rock.
Cells containing rocks which are denoted by the same character are occupied by the same physical rock. Each pair of cells which is occupied by the same rock will be connected. This means that if you label the cells C1 and C2, at least one of the following will be true:
  • C1 and C2 share a side.
  • There exists another cell C3, where C1 and C3 share a side, and C3 is connected to C2.
The character used to denote a rock represents the cost required to destroy that entire rock. The costs are as follows:
  • 'a' - 'z': 1 - 26
  • 'A' - 'Z': 100 - 2,600 (each letter costs 100 more than the previous letter)
  • '1' - '9': 10,000 - 90,000 (each digit costs 10,000 more than the previous digit)
  • '0': 100,000
You must build a road between each pair of cities denoted by the same character. Each road must be a continuous (but not necessarily straight) line which starts in the middle of one city and ends in the middle of the other city. Roads cannot be built outside the boundaries of the map, and roads must not touch any cell which contains a rock (not even the sides or corners of such cells). Return the minimum cost required to destroy all the rocks necessary to build the roads.
 

Definition

    
Class:BuildingRoads
Method:destroyRocks
Parameters:String[]
Returns:int
Method signature:int destroyRocks(String[] field)
(be sure your method is public)
    
 

Notes

-The roads are assumed to be arbitrarily thin, and can intersect each other.
-The roads may pass through any city.
 

Constraints

-field will contain between 2 and 50 elements, inclusive.
-Each element of field will contain between 1 and 50 characters, inclusive.
-Each element of field will contain the same number of characters.
-Each character in field will be '.', 'a'-'z', 'A'-'Z', '0'-'9', '!', '@', '#', or '$'.
-field will contain either zero or two occurrences of '!'.
-field will contain either zero or two occurrences of '@'.
-field will contain either zero or two occurrences of '#'.
-field will contain either zero or two occurrences of '$'.
-There will be at least two cities in field.
-Each pair of cells which is occupied by the same rock will be connected (as described in the problem statement).
 

Examples

0)
    
{"!1.!",
 "aab2"}
Returns: 3


You must destroy the two rocks which cover the purple cells. The total cost is 3.
1)
    
{"#@",
 "A.",
 "A1",
 "@#"}
Returns: 100
2)
    
{"$....",
 "BBBBB",
 "B000B",
 "B0$0B",
 "B000B",
 "BBBBB"}
Returns: 100200
3)
    
{"$a",
 ".B",
 "$3"}
Returns: 0
4)
    
{".#!@.$",
 ".11111",
 "..AB..",
 "33AB..",
 "$3AB..",
 "88888a",
 "#!@..."}
Returns: 30301

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

NetworkSecurity

Graph Theory, Greedy



Used in:

SRM 480

Used as:

Division I Level Two

Writer:

dolphinigle

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10736

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14159&pm=10736

Problem Statement

    NOTE: This problem statement contains images that may not display properly if viewed outside of the applet.



TopCoder Security Agency (TSA) has been hired to secure a network system. In this network, there are several client computers and server computers which for the sake of conciseness will be called clients and servers, respectively. There are several one directional data cables in the network: between clients and from clients to servers. A data path in the network is defined as a series of 2 or more computers C1, C2, C3, ..., CN such that for each i between 1 and N-1, there exists a data cable from Ci to C(i+1). To avoid infinite data loops, the network is acyclic, that is, there does not exist a data path that originates and ends at the same computer. A client C is connected to a server S if there exists a data path originating at C and ending at S.



TSA is going to secure the network by installing data gates on some of the cables. The network is said to be secure if for every pair of connected client and server, there exists at least one data path between them which uses at least one cable on which a data gate is installed.



There are N clients numbered 0 through N-1 and M servers numbered 0 through M-1. The data cables are given as String[] clientCable and String[] serverCable. The j-th character of the i-th element of clientCable is 'Y' if there exists a data cable from client i to client j, or 'N' otherwise. The j-th character of the i-th element of serverCable is 'Y' if there exists a data cable from client i to server j, or 'N' otherwise.



Return the minimum number of data gates that needs to be installed to make the network secure.
 

Definition

    
Class:NetworkSecurity
Method:secureNetwork
Parameters:String[], String[]
Returns:int
Method signature:int secureNetwork(String[] clientCable, String[] serverCable)
(be sure your method is public)
    
 

Constraints

-clientCable will contain between 1 and 50 elements, inclusive.
-Each element of clientCable will contain exactly N characters, where N is the number of elements in clientCable.
-Each character in clientCable will be 'Y' or 'N'.
-The i-th character of the i-th element of clientCable will be 'N'.
-serverCable will contain the same number of elements as clientCable.
-Each element of serverCable will contain between 1 and 50 characters, inclusive.
-All elements of serverCable will contain the same number of characters.
-Each character in serverCable will be 'Y' or 'N'.
-The network will be acyclic as described in the problem statement.
 

Examples

0)
    
{"NYN"
,"NNN"
,"NYN"}
{"YN"
,"YN"
,"NY"}
Returns: 2


All three clients are connected to server 0 and only client 2 is connected to server 1. If the data gates are installed on the two cables as shown in the picture above, then each of the following data paths between a client and server will contain at least one cable on which a data gate is installed:
  • C0->C1->S0
  • C1->S0
  • C2->C1->S0
  • C2->S1
1)
    
{"NN"
,"NN"}
{"NNN"
,"NNN"}
Returns: 0
No client is connected to any server and hence the network is secure.
2)
    
{"NYNN"
,"NNNN"
,"NNNY"
,"NNNN"}
{"YYN"
,"NNN"
,"NNY"
,"NNN"}
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BuildingCities

Graph Theory, Search



Used in:

Member SRM 461

Used as:

Division I Level Two

Writer:

dolphinigle

Testers:

Rustyoldman , timmac , ivan_metelsky , mohamedafattah , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10732

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14181&pm=10732

Problem Statement

    There is a country with N cities. The cities are located on a two-dimensional plane. The coordinates of the i-th city are given in cityX[i] and cityY[i]. The 0-th city is the capital city while the (N-1)-th city is the center of the market (0-based indexing). Each city is assumed to be a point.



The distance that a citizen needs to travel from one city to another is equal to the Euclidian distance between them. A citizen can travel directly from one city to another if the Euclidian distance does not exceed maxDirect (since they can only carry a limited amount of supplies). Hence, if a citizen wants to go from the capital city to the center of the market then he may need to visit some cities in the journey to restock some supplies.



The king wants to reduce the minimum total distance that a citizen needs to travel from the capital city to the center of the market. He wants this minimum distance to not exceed maxTravel. In order to do so he will create some new cities in the country (he can do so at any coordinates not necessarily integer).



Return the minimum number of new cities needed to be built to achieve his target or -1 if it is impossible.
 

Definition

    
Class:BuildingCities
Method:findMinimumCities
Parameters:int, int, int[], int[]
Returns:int
Method signature:int findMinimumCities(int maxDirect, int maxTravel, int[] cityX, int[] cityY)
(be sure your method is public)
    
 

Notes

-The Euclidian distance between two points (X1,Y1) and (X2,Y2) is defined as the square root of ((X1-X2)*(X1-X2)+(Y1-Y2)*(Y1-Y2)).
 

Constraints

-maxDirect and maxTravel will be between 1 and 2000, inclusive.
-cityX and cityY will contain between 2 and 50 elements, inclusive.
-cityX and cityY will contain the same number of elements.
-Each element of cityX and cityY will be between 0 and 2000, inclusive.
-All cities will have distinct locations.
-To avoid precision problems, if the answer for an input is X >= 0, then it will be possible to build X cities in such way that the minimal travel distance between the capital city and the center of the market is at most maxTravel - 1e-5, and any way of building fewer than X cities will result in this minimal distance being at least maxTravel + 1e-5.
 

Examples

0)
    
1
5
{0,0,0,1,2,2,3}
{0,1,2,2,2,1,1}
Returns: 1
Without adding new cities the minimum distance is 6. By building a city at (1,1) the minimum distance can be reduced to 4.
1)
    
3
15
{2,6,10,14}
{2,6,2,6}
Returns: 3
2)
    
2
15
{0,5,2,3,1,8,6,4,7,9,10}
{0,5,2,3,1,8,6,4,7,9,10}
Returns: 0
Sometimes no new cities need to be built.
3)
    
2
5
{0,5}
{0,5}
Returns: -1
The minimum distance between the two cities will always exceed 5.
4)
    
5
1500
{0,1000}
{0,1000}
Returns: 282

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RabbitPuzzle

Dynamic Programming, Graph Theory, Math



Used in:

SRM 463

Used as:

Division I Level Three

Writer:

rng_58

Testers:

PabloGilberto , misof , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10727

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14148&pm=10727

Problem Statement

    NOTE: This problem statement contains images that may not display properly if viewed outside of the applet.



Taro and Hanako are playing Rabbit Puzzle. There are three rabbits and three nests on a line. You are given a long[] rabbits, where each element is the initial position of a single rabbit, and a long[] nests, where each element is the position of a single nest.



They must perform the following routine exactly K times:
  1. Choose two different rabbits A and B, located at points a and b, respectively.
  2. A jumps over B and lands at point 2*b-a.








The jump is not allowed if another rabbit is already at point 2*b-a.







The jump is also not allowed if A jumps over more than one rabbit.











The goal of the puzzle is to have every rabbit be in a nest after the K routines. Note that the i-th rabbit doesn't necessarily have to be in the i-th nest. Return the number of ways to solve this puzzle, modulo 1,000,000,007. Two ways are considered different if at least one jump is different.



 

Definition

    
Class:RabbitPuzzle
Method:theCount
Parameters:long[], long[], int
Returns:int
Method signature:int theCount(long[] rabbits, long[] nests, int K)
(be sure your method is public)
    
 

Constraints

-rabbits will contain exactly 3 elements.
-Each element of rabbits will be between -10^18 and 10^18, inclusive.
-rabbits will be sorted in strictly ascending order.
-nests will contain exactly 3 elements.
-Each element of nests will be between -10^18 and 10^18, inclusive.
-nests will be sorted in strictly ascending order.
-K will be between 1 and 100, inclusive.
 

Examples

0)
    
{0, 5, 8}
{0, 8, 11}
1
Returns: 1
The only solution is moving a rabbit from 5 to 11.
1)
    
{0, 5, 8}
{0, 8, 11}
3
Returns: 5
2)
    
{0, 5, 8}
{0, 8, 11}
2
Returns: 0
They must use exactly 2 jumps. It's impossible to solve this puzzle.
3)
    
{5, 8, 58}
{13, 22, 64}
58
Returns: 0
This puzzle is also impossible.
4)
    
{0, 1, 2}
{1, 2, 3}
100
Returns: 0
This puzzle is also impossible.
5)
    
{5, 8, 58}
{20, 26, 61}
58
Returns: 537851168
6)
    
{67, 281, 2348}
{235, 1394, 3293}
83
Returns: 167142023
7)
    
{-1000000000000000000, 999999999999999998, 999999999999999999}
{-1000000000000000000, 999999999999999999, 1000000000000000000}
5
Returns: 29

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ColorfulStrings

Brute Force, Search



Used in:

SRM 464

Used as:

Division I Level One , Division II Level Two

Writer:

lyrically

Testers:

PabloGilberto , ivan_metelsky , it4.kp

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10724

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14149&pm=10724

Problem Statement

    The product value of a string is the product of all the digits ('0'-'9') in the string. For example, the product value of "123" is 1 * 2 * 3 = 6.

A string is called colorful if it contains only digits and the product value of each of its nonempty contiguous substrings is distinct.



For example, the string "263" has six substrings: "2", "6", "3", "26", "63" and "263". The product values of these substrings are: 2, 6, 3, 2 * 6 = 12, 6 * 3 = 18 and 2 * 6 * 3 = 36, respectively. Since all six product values are distinct, "263" is colorful.

On the other hand, "236" is not colorful because two of its substrings, "6" and "23", have the same product value (6 = 2 * 3).



Return the k-th (1-based) lexicographically smallest colorful string of length n. If there are less than k colorful strings of length n, return an empty String instead.
 

Definition

    
Class:ColorfulStrings
Method:getKth
Parameters:int, int
Returns:String
Method signature:String getKth(int n, int k)
(be sure your method is public)
    
 

Notes

-The lexicographically smaller of two strings is the one that has the smaller character ('0' < '1' < ... < '9') at the first position where they differ.
 

Constraints

-n will be between 1 and 50, inclusive.
-k will be between 1 and 1,000,000,000, inclusive.
 

Examples

0)
    
3
4
Returns: "238"
The first four smallest colorful strings of length 3 are "234", "235", "237" and "238".
1)
    
4
2000
Returns: ""
The number of colorful strings of length 4 is less than 2000.
2)
    
5
1
Returns: "23457"
3)
    
2
22
Returns: "52"
4)
    
6
464
Returns: "257936"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ParkAmusement

Dynamic Programming, Graph Theory, Math



Used in:

SRM 459

Used as:

Division II Level Three

Writer:

gojira_tc

Testers:

PabloGilberto , legakis , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10723

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14145&pm=10723

Problem Statement

    A new ride is opened in an amusement park. It consists of N landings numbered from 0 to N-1. Some of the landings are connected with pipes. All of the landings are at different heights, so the pipes are all inclined and can only be traversed downwards.



A ride-taker begins his ride at some landing. The pipes are long enough that he cannot see where they lead before entering them. Therefore, at each landing, any descending pipe adjacent to it has an equal probability of being used by a ride-taker who reached this landing.



A ride is finished when a ride-taker reaches a landing which has no adjacent descending pipes. There are two types of such landings: exits and crocodile ponds. If the ride-taker reaches the exit landing, his ride is over and he safely returns home. If one reaches the crocodile pond, his trip is also over, but he never returns home.



You're given a String[] landings describing the ride. Element i of landings describes the i-th landing. If the landing is an exit, the i-th character of landings[i] will be 'E' and the rest of the characters will be '0's (zeroes). If it is a crocodile pond, the i-th character will be 'P' and the rest will be '0's. If the landing has at least one adjacent descending pipe, the j-th character of landings[i] will be '1' (one) if a pipe descends from the i-th landing to the j-th, and '0' (zero) otherwise.



A ride-taker began his ride at a randomly chosen landing, used a total of K pipes throughout his descent and safely returned home afterwards. Each of the landings has the same probability of being chosen as the initial landing of the ride. Compute the probability that he started the ride at landing startLanding.
 

Definition

    
Class:ParkAmusement
Method:getProbability
Parameters:String[], int, int
Returns:double
Method signature:double getProbability(String[] landings, int startLanding, int K)
(be sure your method is public)
    
 

Notes

-Your return value must have an absolute or relative error less than 1e-9.
 

Constraints

-landings will contain exactly N elements, where N is between 2 and 50, inclusive.
-Each element of landings will contain exactly N characters.
-Each character in landings will be '0' (zero), '1' (one), 'E', or 'P'.
-If the i-th element of landings contains an 'E', it will contain only one 'E' as its i-th character, and all other characters in that element will be '0'.
-If the i-th element of landings contains a 'P', it will contain only one 'P' as its i-th character, and all other characters in that element will be '0'.
-If the i-th element of landings doesn't contain an 'E' or a 'P', it will contain at least one '1' character. The i-th character of such element will always be '0'.
-K will be between 1 and N-1, inclusive.
-startLanding will be between 0 and N-1, inclusive.
-There will be no cycles in landings, i.e. it's never possible to return to the same landing after descending through several pipes.
-There will be at least one landing from which it is possible to reach an exit using exactly K pipes.
 

Examples

0)
    
{"E000",
 "1000",
 "1000",
 "1000"}
1
1
Returns: 0.3333333333333333
The ride contains 4 landings, one of which is an exit. Each of the other landings has a single pipe descending to the exit landing. Therefore, each of them could be the starting landing with equal probability of 1/3.
1)
    
{"E000",
 "1000",
 "1001",
 "000P"}
1
1
Returns: 0.6666666666666666
This time, there is an exit landing and a crocodile pond. Of the other two landings, the first has a descending pipe only to the exit, while the second is connected both to the exit and to the pond. So, the probability of reaching an exit starting from landing 2 is lower and the chances of ground 1 being the start of the journey increase.
2)
    
{"01000100",
 "00111000",
 "00001010",
 "000E0000",
 "0000E000",
 "00000P00",
 "000000P0",
 "01000000"}
1
2
Returns: 0.14285714285714288
Analyzing the graph above, we can see that landings 0, 1 and 7 could be the starting landings. One can reach an exit from landing 0 using 2 pipes with probability 2/6, from landing 1 with probability 1/6 and from landing 7 with probability 2/3. Therefore, the probability that the ride-taker began from landing 1 is equal to (1/6)/(2/3+2/6+1/6)=1/7.
3)
    
{"0100",
 "0010",
 "0001",
 "000E"}
0
2
Returns: 0.0
Obviously, the only way to get to the exit landing using 2 pipes is from ground 1. Therefore there is no chance that landing 0 was the initial ground.
4)
    
{"E00",
 "0E0",
 "010"}
0
1
Returns: 0.0
Note that some sections of the ride might be disconnected.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ActivateTree

Dynamic Programming, Graph Theory



Used in:

Member SRM 455

Used as:

Division I Level Three

Writer:

maksay

Testers:

Rustyoldman , timmac , StevieT , maksay , K.A.D.R , Seyaua

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10720

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14179&pm=10720

Problem Statement

    

Petya likes oriented graphs, especially rooted trees. He has such a tree described in a String target. Every edge may be in an active or inactive state. Initially every edge is in an inactive state. Petya wants to change the states of all the edges so that they are all active. To do so he has some trees described in a String[] trees in which each element describes a single tree. Initially, every edge in target is inactive and he must activate them by repeating the following process:

  1. He chooses some vertex V from target and some tree T from trees. The pair (V, T) can only be chosen once overall.
  2. He chooses a subtree T' from target that is rooted at V and is isomorphic to T (see notes for a definition if required).
  3. The state of every edge in T' is toggled (i.e., if it was active, it becomes inactive; if it was inactive it becomes active).

Each time he follows the process he incurs a cost that depends on which tree he selected. If he selects trees[i] it costs him costs[i]. Petya also likes the number 5 and so no vertex in target will have more than 5 children. Return the minimum cost of activating all the edges in target or -1 if it is impossible to do so.

target and the trees in trees will be described using the same format:

  • The vertices are indexed sequentially starting with the root as vertex 0.
  • The parent of each vertex in index order is then written in a space-separated list. I.e., if the i-th number written (zero-indexed) is p[i], it means that there is a directed edge from vertex p[i] to vertex i in the tree. Since the root has no parent, the first number in the list will be -1 instead.

 

Definition

    
Class:ActivateTree
Method:minCost
Parameters:String[], String, int[]
Returns:int
Method signature:int minCost(String[] trees, String target, int[] costs)
(be sure your method is public)
    
 

Notes

-Two trees T and T' are isomorphic if there exists a 1-to-1 mapping between the vertices of T and T', such that for each pair of vertices V1 and V2 in T, there is an edge (V1, V2) if and only if and edge exists between the corresponding vertices of T'. I.e., one tree can be transformed into the other simply by relabelling the vertices.
 

Constraints

-target will contain between 1 and 46 characters, inclusive.
-trees will contain between 1 and 5 elements inclusive.
-Each element of trees will contain between 4 and 10 characters.
-target and each element of trees will be single-space delimited lists of integers formatted without leading zeros, with no leading or trailing spaces.
-target will contain between 2 and 16 integers, inclusive.
-Each element of trees will contain between 2 and 5 integers, inclusive.
-The first integer in target and in each element of trees will be -1.
-target and each element of trees will describe valid trees as specified in the problem statement.
-No vertex in the tree represented by target will have more than 5 children.
-costs will contain the same number of elements as trees.
-Each element of costs will be between 0 and 65536, inclusive.
 

Examples

0)
    
{"-1 0"}
"-1 0"
{5}
Returns: 5
1)
    
{"-1 0"}
"-1 0 0"
{5}
Returns: -1
2)
    
{"-1 0","-1 0"}
"-1 0 0"
{1,101}
Returns: 102
Petya can not use the first tree twice in the same position so he has to pay once for each of the trees.
3)
    
{"-1 0","-1 0","-1 0 3 0"}
"-1 0 3 0"
{5,10,21}
Returns: 20
Here it is cheaper to use the first tree twice and the second tree once than to use only the third tree.
4)
    
{"-1 0 1","-1 0 0","-1 0","-1 0 1 0 2"}
"-1 0 0 0 2"
{3885,13122,31377,21317}
Returns: 17007

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MaintainPlanes



Used in:


Used as:



Writer:


Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10704

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14175&pm=10704

Problem Statement

    

Introduction

Airlines have to perform routine maintenance on their fleets. However, they do not want this maintenance to interrupt their flight schedules. You work for AAFE (An Airline that Flies Everywhere) and have been tasked with scheduling the AAFE maintenance crew.



AAFE has N planes in its fleet. Every day, each plane flies a number of routes, ending the day at some location. As the airline flies everywhere, the planes end up scattered all over the world, sometimes even landing in the ocean or at the poles (the planes are all equipped for this).



The maintenance crew can service one plane per night, and getting to the correct location during the day is never a problem. However, they are paid per km traveled (in addition to a base salary and generous healthcare package) so AAFE would like for them to travel as little as possible. Furthermore, if they travel more than 4500km in one day, they will be paid double.

Problem

Your task is thus to determine a schedule for the maintenance crew under which the crew travels as little as possible. The crew will start at a home location (as specified by latitude and longitude) and must service one as-yet-unserviced plane per night for the next N nights. After the final plane has been serviced, the crew will return home for one night off before the next maintenance cycle begins. Night is used loosely in this context, as the crew will end up in many different timezones, and night refers to night UTC.

Implementation Details

You will be given an int N, indicating the number of planes, and an int M indicating the number of cycles. You will also be given the crew's home location as two doubles, start_lat and start_lng. The schedule for the N planes will be given to you as a single double[]. The simulation will have (N+1)*M nights for the M cycles of N planes plus one night off per cycle. The input will thus contain 2 * N * (N+1)*M elements. The ending latitude of plane j on night i of the simulation will be given by element 2 * (i * N + j) of the input. The longitude will be the next element: 2 * (i * N + j) + 1.



The planes are numbered 0..N-1. You should return a int[] with N*M elements indicating the planes to be served in each cycle. The first N elements of your return should be a permutation of the integers 0..N-1, as should the next N and so on.



For example, imagine that there are two planes and two maintenance cycles (N=M=2). The input might look like
{
  10,   0,     40, -90, //ending locations for two planes on day 0
  20,   105,  -25,  43 //day 1
 -20,  -15,   -65, -143 //day 2
  50,  -45,   -35,  13 //day 3
  10,  -175 ,  15,  74 //day 4
 -5,   -85,    25,  18 //day 5
}
Imagine that the maintenance crew starts at 0,0. They need to service planes at the end of days 0,1, 3, and 4. If they service plane 0 on nights 0 and 4, and plane 1 on nights 1 and 3, then their route would be:
0,0 -> 10,0 -> -25,43 -> 0,0 -> -35,13 -> 10,-175 -> 0,0
In this case, you would return {0,1,1,0}.

Scoring

The average cost, AVG, of travel by the crew is determined by the first finding the great circle distance (km) between consecutive points on the crew itinerary. Any of those that are 4500km or more will then be doubled. The average of these costs is then taken. Your score for each individual test case will be 10000/AVG. Your overall score will simply be the sum of your individual scores. If you fail a test case (your program doesn't return an answer, or your answer is invalid) you will receive a 0 for that test case.

Visualizer/Offline Tester

You may download a tool to aid your development at http://www.topcoder.com/contest/problem/MaintainPlanes/vis.html.

Environment & Target Configuration

NVIDIA Tesla C1060 with 4GB of Global Memory

Intel Q8200 CPU

4GB of system memory

Centos 5.3 Linux

NVIDIA GeForce GPU for graphics

Your application should use NVIDIA CUDA 2.3 SDK.

gcc, g++, CUDA 2.3 drivers, tookit and SDK are installed on the servers, and execution path and Library paths setup.
 

Definition

    
Class:MaintainPlanes
Method:schedule
Parameters:int, int, double, double, double[]
Returns:int[]
Method signature:int[] schedule(int M, int N, double home_lat, double home_lng, double[] positions)
(be sure your method is public)
    
 

Notes

-Latitude values will be between -90 and 90, inclusive.
-Longitude values will be between -180 and 180, inclusive
-The Earth is treated as a perfect sphere with radius 6378.1km.
-The distance between two points is calculated as the great circle distance
-Note that this problem uses degrees, not radians.
-There are 50 provisional tests.
-M and N are chosen uniformly. All of the landing points are chosen uniformly over the surface of the earth.
 

Constraints

-N will be between 30 and 100, inclusive.
-M will be between 5 and 30, inclusive.
-The time limit is 20 seconds per test case.
-The CPU memory limit is 1024MB.
 

Examples

0)
    
"1"
Returns: "seed = 1
<br>M = 5
<br>N = 30
<br>"
1)
    
"2"
Returns: "seed = 2
<br>M = 5
<br>N = 40
<br>"
2)
    
"3"
Returns: "seed = 3
<br>M = 11
<br>N = 81
<br>"
3)
    
"4"
Returns: "seed = 4
<br>M = 13
<br>N = 73
<br>"
4)
    
"5"
Returns: "seed = 5
<br>M = 28
<br>N = 86
<br>"
5)
    
"6"
Returns: "seed = 6
<br>M = 18
<br>N = 63
<br>"
6)
    
"7"
Returns: "seed = 7
<br>M = 23
<br>N = 64
<br>"
7)
    
"8"
Returns: "seed = 8
<br>M = 25
<br>N = 93
<br>"
8)
    
"9"
Returns: "seed = 9
<br>M = 30
<br>N = 96
<br>"
9)
    
"10"
Returns: "seed = 10
<br>M = 30
<br>N = 100
<br>"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheHexagonsDivOne

Graph Theory, Simulation



Used in:

SRM 457

Used as:

Division I Level Two

Writer:

vexorian

Testers:

PabloGilberto , ivan_metelsky , Chmel_Tolstiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10702

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14144&pm=10702

Problem Statement

    John and Brus are interested in a new game called "Hexagon Flower". The rules are simple. You are given a flower formed by seven hexagons arranged as follows:







The objective of the game is to place a number in each hexagon of the flower such that all of the following conditions are satisfied:



  • Each number is an integer between 1 and n*2, inclusive.
  • Each number is distinct.
  • For every pair of adjacent hexagons, if the numbers placed in them are a and b, then a%n != b%n.


Given n, return the total number of distinct solutions. Two solutions are considered the same if you can rotate one to form the other.



For example, if n = 4 then:







The top three placements are not valid. The other three placements are valid, but the first two among them are considered equal since one can be rotated to become the other.
 

Definition

    
Class:TheHexagonsDivOne
Method:count
Parameters:int
Returns:long
Method signature:long count(int n)
(be sure your method is public)
    
 

Constraints

-n will be between 1 and 150, inclusive.
 

Examples

0)
    
3
Returns: 0
There are not enough numbers to fill the flower with.
1)
    
4
Returns: 256
2)
    
8
Returns: 3458560
3)
    
20
Returns: 11193888000

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheTriangleBothDivs

Simple Search, Iteration, String Manipulation, String Parsing



Used in:

SRM 457

Used as:

Division I Level One , Division II Level Two

Writer:

vexorian

Testers:

PabloGilberto , ivan_metelsky , Chmel_Tolstiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10696

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14144&pm=10696

Problem Statement

    John and Brus have always been confused by time zones. Their recent promotions to Concorde pilot and copilot do not help. Having to constantly fly through the Bermuda Triangle does not help either. They have therefore purchased a special digital clock that displays the current time in one of 19 time zones, from GMT-9 to GMT+9. The clock displays time in the format "HH:mm GMTof" (quotes for clarity), where HH is the hour of the day (between 00 and 23, inclusive), mm is the number of minutes since the start of the hour (between 00 and 59, inclusive), and of is the offset from "Greenwich Mean Time" (time zone GMT+0) to the current time zone. If the offset is +4, for example, it means the displayed time is 4 hours ahead of the time in GMT+0, and if the offset is -4, it means the time is 4 hours behind the time in GMT+0. GMT+0 will always be displayed with an offset of +0, so the clock will never display it as GMT-0.



In the middle of a flight, John wanted to know what time it was, so he asked Brus to check the clock. To Brus' surprise, the Bermuda Triangle had caused the clock to malfunction, and some of the characters on the display were unrecognizable. You are given the clock's display as a String time, where '?' characters represent the unrecognizable characters. Assuming that all the recognizable characters are accurate, determine what time it is in time zone GMT+0. Return this time formatted as "HH:mm" (quotes for clarity). If there are multiple possible answers, return the one that comes earliest lexicographically. The constraints ensure that at least one result is always possible.
 

Definition

    
Class:TheTriangleBothDivs
Method:fix
Parameters:String
Returns:String
Method signature:String fix(String time)
(be sure your method is public)
    
 

Notes

-String s1 comes before String s2 lexicographically if s1 has a lexicographically smaller character at the first index where they differ.
 

Constraints

-time will contain exactly 11 characters.
-time will be formatted "xx:xx GMTsx" (quotes for clarity).
-Each x in time will be a digit ('0'-'9') or '?'.
-The s in time will be '-','+' or '?'.
-time will represent a valid clock display (as described in the statement) where zero or more of the digits or the '-' or '+' sign have been replaced by '?' characters.
 

Examples

0)
    
"17:45 GMT-4"
Returns: "21:45"
1)
    
"16:?? GMT??"
Returns: "00:00"
There are many possible times the clock could be displaying, for example: "16:00 GMT+8", "16:35 GMT-9", etc. It is possible to choose "00" minutes and the GMT-8 time zone to yield time "00:00" which is the lexicographically first result.
2)
    
"?1:34 GMT-9"
Returns: "06:34"
3)
    
"??:?? GMT??"
Returns: "00:00"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MazeOnFire

Graph Theory, Search, Simulation



Used in:

SRM 467

Used as:

Division II Level Three

Writer:

vexorian

Testers:

PabloGilberto , misof , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10695

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14151&pm=10695

Problem Statement

    NOTE: This problem statement contains images that may not display properly if viewed outside of the applet.



"Maze on Fire" was a not-so-popular electronic game that consisted of a maze built on a grid. Each cell in the grid is empty or contains a wall. Some of the empty cells initially contain fire, and fire propagates after each turn. A playable character is located somewhere in the maze, and its objective is to survive for as many turns as possible before it ends up in a cell that contains fire (at which point, the machine will play a "BURNED!" sound).



Your task is simple enough. You must write an artificial intelligence program that can control the character in such a way that it always survives for as many turns as possible. You are given a String[] that represents the maze. The j-th character of the i-th element of maze represents the cell at row i, column j. Each cell is one of the following:

  • '.' : An empty cell.
  • 'F' : A cell containing fire.
  • '#' : A wall.
  • '$' : The character.


The game is played as follows. During each turn, the character may stay in its current cell or move to an adjacent empty cell which is not on fire. Two cells are considered adjacent if they share a side. After the character's turn, the fire will propagate. Each cell that contains fire in the current turn will set fire to all of its adjacent empty cells. If the cell in which the character is located catches fire, the game will end (and the current turn will count toward the total number of turns survived by the character). Return the maximum possible number of turns the character can survive, or -1 if it is possible for the character to survive indefinitely.
 

Definition

    
Class:MazeOnFire
Method:maximumTurns
Parameters:String[]
Returns:int
Method signature:int maximumTurns(String[] maze)
(be sure your method is public)
    
 

Constraints

-maze will contain between 1 and 50 elements, inclusive.
-Each element of maze will contain between 2 and 50 characters, inclusive.
-All elements of maze will contain the same number of characters.
-Each element of maze will contain only '.', '$', '#' or 'F'.
-maze will contain exactly one '$' character.
 

Examples

0)
    
{"F..",
 ".$.",
 "..."}
Returns: 4
The best move in this case is to take the character to the bottom right cell. Fire will reach that cell after the fourth turn. The four turns are detailed in the following picture:



1)
    
{".F#...",
 "F....#",
 ".F###.",
 "F.#.$.",
 "F.#..."}
Returns: -1
There is a wall barrier between the character and the multiple cells that are on fire. It is possible to survive indefinitely.
2)
    
{"....#.",
 "$##.#.",
 ".#..#F",
 ".F#.#.",
 "..#..."}
Returns: 7
3)
    
{"...$..",
 "..#...",
 "..###.",
 "..#...",
 "F.#.F."}
Returns: 7
Sometimes it is best not to move the character at all.
4)
    
{".F....F.",
 ".#.##.#.",
 ".#....#.",
 "F.$##..F",
 ".#....#.",
 ".###.##.",
 ".F....F."}
Returns: 4

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LongJourney

Dynamic Programming, Graph Theory, Search



Used in:

TCO10 Round 5

Used as:

Division I Level Two

Writer:

StevieT

Testers:

PabloGilberto , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10678

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14283&pm=10678

Problem Statement

    Alice is about to set out in her car on a long journey. Her car's fuel tank can only carry fuelTank units of fuel, so she may have to stop at gas stations along the way to refuel. Prices vary across different stations, so she needs to plan ahead to minimize the total cost of the journey.



The network of roads Alice is driving on is represented by an undirected graph with N nodes, in which she starts at node 0 and wishes to get to node 1. Initially, there is no fuel in her car's fuel tank. There is a fuel station located at each node and the cost per unit fuel at node i is fuelCost[i]. The graph is described by a String[] roads. The concatenation of the elements of roads forms a space-separated list of edges. Each edge is formatted "i,j,fuel" (quotes for clarity), in which i, j and fuel are integers formatted without leading zeros. This denotes that there is a bidirectional road connecting nodes i and j and fuel units of fuel will be consumed from the fuel tank in traversing this road. Alice doesn't want to end up stranded, so she cannot traverse a road with less than fuel units of fuel in the tank (although she can safely drive the road with exactly enough fuel).



Return the minimum cost of completing the journey or -1 if it is impossible to get from node 0 to node 1.
 

Definition

    
Class:LongJourney
Method:minimumCost
Parameters:int[], int, String[]
Returns:long
Method signature:long minimumCost(int[] fuelPrices, int fuelTank, String[] roads)
(be sure your method is public)
    
 

Notes

-There is no limit to the amount of fuel that Alice can buy at each node.
 

Constraints

-fuelPrices will contain between 2 and 50 elements, inclusive.
-Each element of fuelPrices will be between 1 and 1000000 (10^6), inclusive.
-fuelTank will be between 1 and 1000000 (10^6), inclusive.
-roads will contain between 1 and 50 elements, inclusive.
-Each element of roads will contain between 1 and 50 characters, inclusive.
-The concatenation of the elements of roads will be a single-space-separated list of edges (as described in the problem statement), without leading or trailing spaces.
-In each edge in roads, i and j will be between 0 and N-1, inclusive, where N is the number of elements in fuelTank.
-In each edge in roads, i will be strictly less than j.
-In each edge in roads, fuel will be between 1 and fuelTank, inclusive.
-The i, j pairs of the edges in roads will be distinct.
 

Examples

0)
    
{5,6,1,2}
100
{"0,2,2 "
,"0,3,5 "
,"1,3,3"}
Returns: 20
Here, the 4 fuel stops are spread along a single road:



Station   2--0-----3---1
Price     1  5     2   6


Fuel is very cheap at station 2 and in an optimal trip Alice buys 2 units of fuel at station 0 for cost 10, then travels to station 2 and buys 10 units of fuel there for cost 10. She then drives to her final destination without stopping again.
1)
    
{5,6,1,2}
100
{"0,2,2 "
,"0,3,1 "
,"1,3,7"}
Returns: 19
This is the same case as example 0, but with fuel station 3 moved in position along the road.



Station   2--0-3-------1
Price     1  5 2       6


This time, it is cheaper to simply buy a unit of fuel at station 0, then drive to station 3 and buy the remaining fuel required there.
2)
    
{10,15,5,20}
500
{"0,2,50","0 2,3,50"}
Returns: -1
There is no way to get to the destination here.
3)
    
{8131,12392,4152,7482,124208,1,1800,19,33791,2,4970,635157,7089,194,279,162627}
985516
{"0,2,885843 0,5,948680 0,6,814375 0,7,254140 0,9,96"
,"5704 0,11,950391 0,12,2234 0,13,666704 0,14,757770"
," 1,4,233 1,5,850136 1,8,792847 1,9,62147 1,13,8726"
,"80 1,14,827511 1,15,253774 2,3,4831 2,4,63 2,5,660"
,"053 2,6,1079 2,7,379766 2,8,681543 2,9,910853 2,11"
,",871528 2,12,587492 2,13,762963 2,14,3761 3,4,3462"
,"62 3,5,147581 3,6,881103 3,8,426200 3,9,39902 3,10"
,",915751 3,11,293781 3,14,722019 3,15,394147 4,5,39"
,"5608 4,8,972273 4,9,855758 4,10,423924 4,12,974268"
," 4,15,931000 5,6,831319 5,7,76 5,8,53136 5,9,42289"
,"6 5,11,12626 5,13,220080 5,14,321058 5,15,6 6,7,51"
,"0462 6,10,926807 6,11,659470 6,12,702857 6,13,8555"
,"66 6,14,719994 6,15,868043 7,10,821770 7,13,216703"
," 7,15,758397 8,9,267740 8,10,772522 8,13,279514 9,"
,"10,24592 9,11,680535 9,12,624855 9,14,132484 10,15"
,",869307 11,12,28 11,13,493421 11,14,590457 12,14,3"
,"16607 13,14,542254"}
Returns: 108021568
4)
    
{1000000,1000000}
1000000
{"0,1,1000000"}
Returns: 1000000000000
Be careful of overflow.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TransportationNetwork

Graph Theory, Greedy, Sorting



Used in:

Pilot 2

Used as:

Division I Level Two , Division II Level Three

Writer:

vexorian

Testers:

Rustyoldman , timmac , Nickolas , it4.kp , StevieT

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10654

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13952&pm=10654

Problem Statement

    Little Johnny has just been named minister of transportation for the republic of Feudalia. Feudalia currently lacks any means of transportation between its cities, which has prompted Little Johnny to begin the planning process for a new transportation network for the twentieth century. To do so, Feudalia may build roads to connect pairs of cities and may also build airports within cities. Each airport costs airportCost to build. The construction of a road of length L will cost roadCost x L. A road must be a straight line between two cities. Although roads may cross, road travel between two cities must be done in a straight line. Air travel is possible between two cities if and only if both cities have an airport. Little Johnny requires every city in Feudalia to be reachable from all the other cities. Formally, a city B is reachable from a city A if any of the following conditions is true:

  • There is a straight line road between A and B.
  • Both A and B contain airports.
  • There exists some city C, such that B is reachable from C and C is reachable A.


You are given the coordinates of the cities as two int[] cityX and cityY such the i-th city will have cartesian coordinates (cityX[i], cityY[i]). You are also given roadCost and airportCost. Return the minimum cost the ministry of transportation will have to incur.
 

Definition

    
Class:TransportationNetwork
Method:minCost
Parameters:int[], int[], double, double
Returns:double
Method signature:double minCost(int[] cityX, int[] cityY, double roadCost, double airportCost)
(be sure your method is public)
    
 

Constraints

-cityX will have between 1 and 150 elements, inclusive.
-cityY will have the same number of elements as cityX.
-Each element of cityX and cityY will be between 0 and 1000000, inclusive.
-roadCost will be between 0 and 3.0, inclusive.
-airportCost will be between 0 and 10000000, inclusive.
-The locations of the cites will be distinct.
 

Examples

0)
    
{0, 0, 400, 400}
{0, 100, 0, 100}
1.0
150.0
Returns: 500.0
An optimal transportation network would be: - Build roads connecting city 0 with city 1 and city 2 with city 3. - Build airports at cities 0 and 2.
1)
    
{0, 0, 400, 400, 2000}
{0, 100, 0, 100, 2000}
1.0
500
Returns: 1600.0
2)
    
{0, 100, 200, 300, 400,2000,2100,2200}
{0, 100, 200, 300, 400,2000,2100,2200}
0.5
200
Returns: 824.2640687119285
3)
    
{798, 915, 797, 463, 895, 523, 959, 702, 235, 523}
{126, 25, 402, 45, 841, 762, 982, 605, 616, 78}
1.66
300
Returns: 2727.2895312339606

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Problem Statement

    

Image Processing using GPU Accelerated Connected Component Labeling

Introduction

High performance image processing is the foundation of many applications including machine vision, real time object recognition, security and many other applications. One of the common processing steps in many of these applications is connected component labeling (CCL). CCL is a simple, but computationally intensive process.

CCL can be defined as identifying objects within a graph of elements which have the same identifiable property and are connected.

A series of high resolution digital images will be provided. This challenge is to process these high resolution images to identify all objects/areas consisting of groups of adjacent pixels of the same color within a specified threshold.

The implementation will be checked for correctness and total performance.

Input

Each image will be given to you as a int[] in row-major order (first pixel is upper left). Each pixel will be have its three color channels encoded in a single integer. The lowest order 8 bits will give the blue channel, the next highest 8 bits the green channel, and the next highest 8 bits the red channel. You will also be given W, the width of the image.

Two other parameters will control how you find the connected components. The first is degree_of_connectivity and indicates whether diagonal pixels should be considered adjacent. If degree_of_connectivity is 4, then only the 4 adjacent pixels should be considered adjacent. If it is 8, then the diagonal ones should be considered adjacent also. Finally, a int threshold will be provided. Two adjacent pixels are considered to be connected if the sum of the differences in their color components is not more than threshold. That is, if

|R1-R0| + |G1-G0| + |B1-B0| <= threshold

Output

You should return a int[] which is the same size as the input. Each element should specify the index of the connected component that pixel is in. The index of a connected component is the smallest pixel index (index into the input array) of any pixel in that component.

For example, consider the 10x10 image shown here:
If the threshold were set to 300, and degree_of_connectivity were 4, we would decompose it into the 6 connected components shown here:
The cyan one would have all its pixels labeled 0, since it's lowest indexed pixel is the upper left corner. The yellow component would have all its pixels labeled 12, since that is the index of the upper left corner of the yellow box. Moving to the end, the lowest index of the large orange region is 32. Note that if degree_of_connectivity had been 8, there would have only been two connected components.

Resources

Wikipedia has a comprehensive write up of connected component labeling at http://en.wikipedia.org/wiki/Connected_Component_Labeling. This task uses a 2D mesh of connected pixels so the generalized case of CCL or CCA of an arbitrarily connected graph does not have to be solved.

There have also been discussions about the use of NVIDIA CUDA Architecture for CCA in published papers and also on NVIDIA CUDA Developer forums.

An excellent, easy to follow, paper on the subject can be found at: http://www.massey.ac.nz/~kahawick/cstn/089/cstn-089.pdf In this paper, section 4 "Hypercubic Mesh Graphs" may be helpful.

Environment & Target Configuration

NVIDIA Tesla C1060 with 4GB of Global Memory

Intel Q8200 CPU

4GB of system memory

Centos 5.3 Linux

NVIDIA GeForce GPU for graphics

Your application should use NVIDIA CUDA 2.3 SDK.

gcc, g++, CUDA 2.3 drivers, tookit and SDK are installed on the servers, and execution path and Library paths setup.

Testing and Scoring

Your score for each test case will be a 0 if you fail to return the right answer, and otherwise will be your runtime in milliseconds. Your overall final score will be the total number of pixels processed divided by your total runtime in seconds. Note that the sum is taken before division is done, giving more weight to larger test cases. Each incorrect answer (a 0 above) will halve your score, in addition to penalizing your total time 60 seconds.
 

Definition

    
Class:CCL
Method:cuda_ccl
Parameters:int[], int, int, int
Returns:int[]
Method signature:int[] cuda_ccl(int[] image, int W, int degree_of_connectivity, int threshold)
(be sure your method is public)
    
 

Notes

-The final scores will be scaled by a constant factor.
-To facilitate debugging, the number of test cases that you fail will be encoded as the number of hundredths in your provisional score. So, a score of 234.04 would indicate that your score was about 234 (when calculated as above) and that you failed 4 of the test cases.
-IMPORTANT HINT: you can change the method signature to pass by reference. A popular choices is:
vector <int> cuda_ccl(vector <int> & image, int W, int degree_of_connectivity, int threshold)
This may be necessary to stay within the memory limit for the larger test cases, and should help your runtime. Also, you may use all of the memory available on the nVidia device. See http://forums.topcoder.com/?module=Thread&threadID=651355&start=0&mc=14#1144482.
 

Constraints

-The images will have up to 300,000,000 pixels and neither side will have more than 20,000 pixels.
-You have up to 1 minute per image.
-The system memory limit is 2500M. You may use all of the device memory.
 

Examples

0)
    
"64by64_image1.bmp 4 0"
Returns: 
"<a href=/contest/problem/CCL/64by64_image1.bmp>Input Image</a><br>degree_of_connectivity = 4<br>threshold = 0<br>"
1)
    
"64by64_image1.bmp 8 30"
Returns: 
"<a href=/contest/problem/CCL/64by64_image1.bmp>Input Image</a><br>degree_of_connectivity = 8<br>threshold = 30<br>"
2)
    
"100by300_image1.bmp 4 25"
Returns: 
"<a href=/contest/problem/CCL/100by300_image1.bmp>Input Image</a><br>degree_of_connectivity = 4<br>threshold = 25<br>"
3)
    
"100by300_image1.bmp 8 0"
Returns: 
"<a href=/contest/problem/CCL/100by300_image1.bmp>Input Image</a><br>degree_of_connectivity = 8<br>threshold = 0<br>"
4)
    
"1Kby768_image1.bmp 8 0"
Returns: 
"<a href=/contest/problem/CCL/1Kby768_image1.bmp>Input Image</a><br>degree_of_connectivity = 8<br>threshold = 0<br>"
5)
    
"4Kby4K_image2.bmp 4 25"
Returns: 
"<a href=/contest/problem/CCL/4Kby4K_image2.bmp>Input Image</a><br>degree_of_connectivity = 4<br>threshold = 25<br>"
6)
    
"hs-2007-13-e-full_jpg.jpg 4 10"
Returns: 
"<a href=/contest/problem/CCL/hs-2007-13-e-full_jpg.jpg>Input Image</a><br>degree_of_connectivity = 4<br>threshold = 10<br>"
7)
    
"hs-2008-23-a-full_jpg.jpg 8 60"
Returns: 
"<a href=/contest/problem/CCL/hs-2008-23-a-full_jpg.jpg>Input Image</a><br>degree_of_connectivity = 8<br>threshold = 60<br>"
8)
    
"hs-2008-31-a-full_jpg.jpg 4 10"
Returns: 
"<a href=/contest/problem/CCL/hs-2008-31-a-full_jpg.jpg>Input Image</a><br>degree_of_connectivity = 4<br>threshold = 10<br>"
9)
    
"hs-2009-05-a-full_jpg.jpg 4 30"
Returns: 
"<a href=/contest/problem/CCL/hs-2009-05-a-full_jpg.jpg>Input Image</a><br>degree_of_connectivity = 4<br>threshold = 30<br>"
10)
    
"hs-2009-23-b-full_jpg.jpg 8 60"
Returns: 
"<a href=/contest/problem/CCL/hs-2009-23-b-full_jpg.jpg>Input Image</a><br>degree_of_connectivity = 8<br>threshold = 60<br>"
11)
    
"PGM_ganymede_map.bmp 4 30"
Returns: 
"<a href=/contest/problem/CCL/PGM_ganymede_map.bmp>Input Image</a><br>degree_of_connectivity = 4<br>threshold = 30<br>"
12)
    
"venus_aphrodite_terra.bmp 4 10"
Returns: 
"<a href=/contest/problem/CCL/venus_aphrodite_terra.bmp>Input Image</a><br>degree_of_connectivity = 4<br>threshold = 10<br>"
13)
    
"cerberus_enhanced.bmp 8 60"
Returns: 
"<a href=/contest/problem/CCL/cerberus_enhanced.bmp>Input Image</a><br>degree_of_connectivity = 8<br>threshold = 60<br>"
14)
    
"hs-2004-28-b-full_jpg.jpg 8 60"
Returns: 
"<a href=/contest/problem/CCL/hs-2004-28-b-full_jpg.jpg>Input Image</a><br>degree_of_connectivity = 8<br>threshold = 60<br>"
15)
    
"hs-2004-30-a-full_jpg.jpg 4 30"
Returns: 
"<a href=/contest/problem/CCL/hs-2004-30-a-full_jpg.jpg>Input Image</a><br>degree_of_connectivity = 4<br>threshold = 30<br>"
16)
    
"hs-2006-01-a-hires_jpg.jpg 8 60"
Returns: 
"<a href=/contest/problem/CCL/hs-2006-01-a-hires_jpg.jpg>Input Image</a><br>degree_of_connectivity = 8<br>threshold = 60<br>"
17)
    
"hs-2003-11-a-full_jpg.jpg 4 10"
Returns: 
"<a href=/contest/problem/CCL/hs-2003-11-a-full_jpg.jpg>Input Image</a><br>degree_of_connectivity = 4<br>threshold = 10<br>"
18)
    
"hs-2007-16-a-full_jpg.jpg 8 30"
Returns: 
"<a href=/contest/problem/CCL/hs-2007-16-a-full_jpg.jpg>Input Image</a><br>degree_of_connectivity = 8<br>threshold = 30<br>"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TwistedMatrix

Brute Force, Simulation, String Manipulation



Used in:

Pilot 2

Used as:

Division I Level One , Division II Level Two

Writer:

vexorian

Testers:

Rustyoldman , timmac , Nickolas , it4.kp , StevieT

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10638

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13952&pm=10638

Problem Statement

    NOTE: This problem statement contains images that may not display properly if viewed outside of the applet.



"Twisted Matrix" is a strange game in which you are given a binary matrix (containing only '1' or '0') and must perform a series of twist operations in order to reach a certain goal matrix. A twist operation involves taking any 2x2 block inside the matrix and then rotating the elements within the block 90 degrees clockwise or counterclockwise.

The following image shows two consecutive twist operations performed on a initial matrix.





Little Johnny has won the first prize in a world wide Twisted Matrix tournament. Unfortunately, his friends do not believe him. The situation is not helped by the fact that little Johnny has a very bad memory and cannot clearly remember the last move he made in order to reach the goal matrix in the finals. He only partially remembers the last two matrices in the game. You are given matrices A and B. Each matrix is given as String[], the j-th character of the i-th element of each String[] describes the cell at row i, column j of the matrix. Each cell contains '0' or '1' if little Johnny remembers the number in that cell or '?' otherwise. Matrix B was the last matrix in the game and A was the matrix preceeding it, which means that performing one twist operation on A must transform it into B. Return a String[] representing the complete contents of the matrix B. If there are many valid solutions then return the lexicographically first solution. If no solution is possible then return an empty String[].
 

Definition

    
Class:TwistedMatrix
Method:solve
Parameters:String[], String[]
Returns:String[]
Method signature:String[] solve(String[] A, String[] B)
(be sure your method is public)
    
 

Notes

-The lexicographically first of two matrices is the one with the lexicographically earlier row at the first row at which they differ.
-The lexicographically first of two rows is the one with the smaller cell at the first column at which they differ.
 

Constraints

-A and B will each contain N elements, where N is between 2 and 30, inclusive.
-Each element of A and B will contain M characters, where M is between 2 and 30, inclusive.
-Each character in each element of A and B will be '1', '0' or '?'.
 

Examples

0)
    
{"1000",
 "0000",
 "0000",
 "0000"}
{"0000",
 "?000",
 "0000",
 "0000"}
Returns: {"0000", "1000", "0000", "0000" }
1)
    
{"11",
 "01"}
{"??",
 "??"}
Returns: {"01", "11" }
Another possibility is {"11","10"} but {"01","11"} comes earlier lexicographically.
2)
    
{"000",
 "0?0",
 "000"}
{"111",
 "1?1",
 "111"}
Returns: { }
3)
    
{"?1111",
 "11111",
 "11011",
 "10111"}
{"?1111",
 "11111",
 "1??11",
 "1??11"}
Returns: {"01111", "11111", "10011", "11111" }
4)
    
{"00111",
 "00111",
 "11111",
 "11111"}
{"??1??",
 "??1??",
 "?????",
 "?????"}
Returns: {"00111", "00111", "11111", "11111" }
In order to get the lexicographically earliest solution, you must rotate the 2x2 block containing only zeros. Note that this movement does not modify the matrix, but it is still valid.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PizzaDelivery

Brute Force, Graph Theory



Used in:

SRM 451

Used as:

Division II Level Three

Writer:

vexorian

Testers:

PabloGilberto , bmerry , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10634

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13905&pm=10634

Problem Statement

    Tom McCoffee owns the only pizza delivery place in the mountains. The terrain is represented as a rectangular grid of squares, where each square either contains a building or is empty. Each empty square has an integer height between 0 and 9, inclusive. Today, each building in the area has ordered one pizza, and Tom must use his two delivery boys to fulfill all the orders in the shortest total amount of time possible.



From each square in the grid, you can only move to adjacent squares. Two squares are adjacent if they share an edge. You can only move between two empty squares if the absolute difference of their heights is less than or equal to 1. If the height difference is 0, it takes 1 minute to make the move, and if the absolute height difference is 1, it takes 3 minutes.



You can always move to a building from any of its adjacent squares and vice versa, regardless of height. This is because all buildings are taller than the highest terrain, and each building has entrances and exits for all its adjacent squares at the correct heights. Moving to or from a square containing a building takes 2 minutes. The delivery boys are allowed to enter buildings even if they are not their final destinations. Note that the pizza place itself is also a building.



Each delivery boy can only carry one pizza at a time. This means that after each delivery, the delivery boy must return to the pizza place to pick up another pizza if there are more deliveries left to do. You are given a String[] terrain, where the j-th character of the i-th element represents the square at row i, column j of the terrain. '$' represents a building from which a pizza was ordered, 'X' represents the location of the restaurant, and the digits '0'-'9' represent the heights of empty squares. The initial time is 0. Return the minimum time in minutes at which the last delivery can be made. If it is not possible to deliver all the pizzas, return -1 instead.
 

Definition

    
Class:PizzaDelivery
Method:deliverAll
Parameters:String[]
Returns:int
Method signature:int deliverAll(String[] terrain)
(be sure your method is public)
    
 

Constraints

-terrain will contain between 2 and 50 elements, inclusive.
-Each element of terrain will contain between 2 and 50 characters, inclusive.
-Each element of terrain will contain the same number of characters.
-Each character in terrain will be 'X', '$' or a digit between '0' and '9', inclusive.
-terrain will contain between 1 and 20 '$' characters, inclusive.
-terrain will contain exactly one 'X' character.
 

Examples

0)
    
{"3442211",
 "34$221X",
 "3442211"}
Returns: 8
Only one pizza boy is needed for this single delivery.

The pizza boy must first take two minutes to go from the restaurant to the cell to its left.

Then he must climb from the cell of height '1' to the left cell of height '2' , taking 3 minutes.

The movement between two cells of height '2' takes one minute.

He finally needs two more minutes to go from the cell of height '2' to the only building in the area.
1)
    
{"001000$",
 "$010X0$",
 "0010000"}
Returns: 13
This time there are three buildings, and an optimal solution is as follows:
  • 00:00 -> Pizza boy #1 takes the pizza assigned for the left building.
  • 00:00 -> Pizza boy #2 takes the pizza assigned for the right building.
  • 00:04 -> Pizza boy #2 delivers the pizza to the right building.
  • 00:08 -> Pizza boy #2 arrives back at the restaurant, takes the pizza for the top-right building.
  • 00:10 -> Pizza boy #1 delivers the pizza to the left building.
  • 00:13 -> Pizza boy #2 delivers the pizza to the top-right building.
2)
    
{"001000$",
 "$010X0$",
 "0010000",
 "2232222",
 "2222222",
 "111$111"}
Returns: -1
The irregular terrain blocks deliveries to the bottom building.
3)
    
{"001000$",
 "$010X0$",
 "0010000",
 "1232222",
 "2222222",
 "111$111"}
Returns: 28
This time, there is a possible path connecting the restaurant and the bottom building.
4)
    
{"X$$",
 "$$$"}
Returns: 14

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SteeplechaseTrack

Graph Theory



Used in:

SRM 462

Used as:

Division II Level Three

Writer:

Nickolas

Testers:

PabloGilberto , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10594

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14147&pm=10594

Problem Statement

    Your company is going to sponsor a steeplechase horse race at your local racecourse. As a sponsor, you can choose the exact route of the race, and you want it to be as hard as possible.



The racecourse contains a startling line, a finish line, and several fences connected with tracks. Horses start at the starting line, run along the tracks, jump over all fences along the way, and end at the finish line.



You are given a String[] fences where the i-th element describes the i-th fence, and contains exactly three digits between '0' and '9', inclusive. The first digit is the complexity of jumping over the fence. The second digit is the complexity of running from the starting line to the fence. If it is '0', that means there is no track between the starting line and the fence. The third digit is the complexity of running from the fence to the finish line. If it is '0', that means there is no track between the fence and the finish line.



You are also given a String[] tracks describing the tracks connecting the fences. The j-th character of the i-th element of tracks is the complexity of running from fence i to fence j. If that character is '0', that means there is no track from fence i to fence j. It is possible for a track to exist between a fence and itself. Note that all tracks are one-way tracks. If there's a track from fence i to fence j, there isn't necessarily a track from fence j to fence i. Also, complexities are not symmetrical, so the complexity of running from fence i to fence j may be different from the complexity of running from fence j to fence i.



A valid route for the race is a sequence of fences with indices i0, i1, ..., in-1 for which all of the following conditions are satisfied:
  • There is a track from the starting line to fence i0.
  • There is a track from fence ik to fence ik+1 for 0 <= k <= n-2.
  • There is a track from fence in-1 to the finish line.
Note that the same fence may be used multiple times within a route. Each time the horse runs along a track or jumps over a fence, the corresponding complexity is added to the total complexity for the route. Return the maximal total complexity for a valid route containing at most N fences. If the same fence appears multiple times within the route, each occurrence counts toward the total number of fences. If it is impossible to hold a race which satisfies the constraints on the given racecourse, return -1 instead.
 

Definition

    
Class:SteeplechaseTrack
Method:maxComplexity
Parameters:String[], String[], int
Returns:int
Method signature:int maxComplexity(String[] fences, String[] tracks, int N)
(be sure your method is public)
    
 

Constraints

-fences will contain between 1 and 50 elements, inclusive.
-Each element of fences will contain exactly 3 characters.
-tracks will contain the same number of elements as fences.
-Each element of tracks will contain the same number of characters as the number of elements in fences.
-Each character in fences and tracks will be between '0' and '9', inclusive.
-Character 0 of each element of fences will not be '0'.
-N will be between 1 and 100, inclusive.
 

Examples

0)
    
{"310",
 "300",
 "301"}
{"010",
 "001",
 "000"}
4
Returns: 13
You are allowed to use as many as four fences, but the only valid route for this racecourse is start-0-1-2-finish.
1)
    
{"923"}
{"1"}
100
Returns: 1004
This route consists of 100 jumps over the only fence and 99 runs around this fence, for a total complexity 2 + 100*9 + 99*1 + 3 = 1004.
2)
    
{"111",
 "222",
 "333"}
{"743",
 "985",
 "380"}
1
Returns: 9
With only one fence allowed, the complexity of a route is the sum of the following complexities: running from the starting line to the fence, jumping over the fence, and running from the fence to the finish line.
3)
    
{"101",
 "202",
 "303"}
{"659",
 "431",
 "770"}
5
Returns: -1
There are no tracks leading from the starting line to a fence, so no valid routes can be constructed.
4)
    
{"693",
 "982",
 "236"}
{"603",
 "986",
 "780"}
10
Returns: 172

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PeopleYouMayKnow

Graph Theory



Used in:

SRM 447

Used as:

Division I Level Two

Writer:

Gluk

Testers:

PabloGilberto , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10580

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13901&pm=10580

Problem Statement

    

Tim wants to improve "People You May Know" feature of Facebook. This is a feature that attempts to automatically connect people who may know each other in reality, but haven't yet added each other as friends on Facebook.



Friendship on Facebook is symmetric, meaning that if B is a friend of A, then A is also a friend of B. However, it is not necessarily transitive, so if A and B are friends and B and C are friends, then A and C are not necessarily friends.



Tim has defined the term "n-friends" as follows. If two people are friends, they are called 1-friends. For n >= 1, two people A and B are called (n+1)-friends if A and B are n-friends, or if there exists a person C such that A and C are n-friends and C and B are friends.

To determine how likely it is that two people know each other, Tim has introduced the concept of a "Distance Score". If two people A and B are not friends, then their Distance Score is the fewest number of people (other than A and B themselves) who must be removed from the network in order for A and B to not be 3-friends. The higher the Distance Score, the more likely it is that A and B know each other.



You are given String[] friends containing exactly N elements, where N is the number of people in the network. People are numbered from 0 to N-1. The j-th character of the i-th element of friends is 'Y' if i and j are friends, and 'N' otherwise. Return the Distance Score for person1 and person2.

 

Definition

    
Class:PeopleYouMayKnow
Method:maximalScore
Parameters:String[], int, int
Returns:int
Method signature:int maximalScore(String[] friends, int person1, int person2)
(be sure your method is public)
    
 

Constraints

-friends will contain N elements, where N is between 2 and 40, inclusive.

-Each element of friends will contain exactly N characters.

-Each character in friends will be 'Y' or 'N'.

-For all i and j, friends[i][j] will be equal to friends[j][i].

-For all i, friends[i][i] will be equal to 'N'.

-person1 and person2 will each be between 0 and N-1, inclusive.

-person1 and person2 will not be equal.

-friends[person1][person2] will be equal to 'N'.
 

Examples

0)
    
{"NN"
,"NN"}
0
1
Returns: 0
You don't need to remove any people.
1)
    
{"NYNN"
,"YNYN"
,"NYNY"
,"NNYN"}
0
3
Returns: 1
You need to remove person 1 or person 2.
2)
    
{"NYNYYYN"
,"YNYNNYY"
,"NYNNNNY"
,"YNNNNNN"
,"YNNNNYN"
,"YYNNYNY"
,"NYYNNYN"}
2
3
Returns: 1
You need to remove person 0 or person 1.
3)
    
{"NYYYYNNNN"
,"YNNNNYYYN"
,"YNNNNNNYN"
,"YNNNNNNYN"
,"YNNNNNNNY"
,"NYNNNNNNY"
,"NYNNNNNNY"
,"NYYYNNNNY"
,"NNNNYYYYN"}
8
0
Returns: 3
You need to remove person 4 (who knows both 0 and 8), person 1 (friend of 0) and person 7 (friend of 8).

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ImportsList

Graph Theory, Greedy



Used in:

SRM 447

Used as:

Division II Level Three

Writer:

Gluk

Testers:

PabloGilberto , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10579

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13901&pm=10579

Problem Statement

    Every big project contains multiple scripts, each of which may require access to other scripts within the project. Each script contains an import list containing zero or more other scripts. A script has access to all the scripts in its import list, and it also has access to all the scripts that the scripts in its import list have access to. More formally, a script A has access to a script B if and only if there exists a sequence of scripts S[0] = A, S[1], ..., S[k] = B, where k >= 1 and for each i, where 0 <= i < k, script S[i] contains script S[i+1] in its import list. There is an important restriction on the usage of import lists: a script must not have access to itself.

You are given the requirements for your project as a String[] requires. It contains exactly N elements, where N is the number of scripts in the project. Character j of element i of requires is 'Y' if script i must have access to script j, and 'N' otherwise. You must generate the import list for each script in such a way that all the requirements are satisfied. This means that each script must have access to all its required scripts, and not have access to unrequired scripts (including itself). The total number of scripts in all the import lists of all the scripts must be as small as possible (if several import lists contain the same script, each occurrence of that script counts toward the total). Return a int[] containing exactly N elements, where element i is the number of scripts in the import list for script i.
 

Definition

    
Class:ImportsList
Method:importsCount
Parameters:String[]
Returns:int[]
Method signature:int[] importsCount(String[] requires)
(be sure your method is public)
    
 

Notes

-Under the given constraints, there always exists exactly one way to generate import lists with the smallest total number of scripts.
 

Constraints

-requires will contain between 1 and 50 elements, inclusive.

-Each element of requires will contain exactly N characters 'Y' or 'N', where N is the number of elements in requires.

-If the j-th character in the i-th element of requires is 'Y' and the k-th character in the j-th element of requires is 'Y', then the k-th character in the i-th element of requires will be 'Y'.

-The i-th character in i-th element of requires will be 'N'.
 

Examples

0)
    
{"NNN"
,"NNN"
,"NNN"}
Returns: {0, 0, 0 }
None of these scripts require other scripts, so no imports are needed.
1)
    
{"NYYY"
,"NNYY"
,"NNNY"
,"NNNN"}
Returns: {1, 1, 1, 0 }
Each script needs to import the next one.
2)
    
{"NNNNY"
,"NNNNY"
,"YNNNY"
,"NNNNN"
,"NNNNN"}
Returns: {1, 1, 1, 0, 0 }
Script 2 must import script 0 and each of the scripts 0 and 1 must import script 4.
3)
    
{"NYYNYNYYYNYYNYNN"
,"NNNNNNNNNNNNNNNN"
,"NNNNNNNNNNYNNNNN"
,"NNNNNNNNNYNNYNNN"
,"NYNNNNYNNNYYNNNN"
,"NYNNYNYNYNYYNNNN"
,"NNNNNNNNNNYNNNNN"
,"NNYNNNYNYNYNNNNN"
,"NNNNNNYNNNYNNNNN"
,"NNNNNNNNNNNNYNNN"
,"NNNNNNNNNNNNNNNN"
,"NNNNNNNNNNNNNNNN"
,"NNNNNNNNNNNNNNNN"
,"NNNNNNYNNNYNNNNN"
,"YYYYYNYYYYYYYYNY"
,"NYYYNNYNNYYNYYNN"}
Returns: {3, 0, 1, 1, 3, 2, 1, 2, 1, 1, 0, 0, 0, 1, 2, 4 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AgentMatching



Used in:

AgentMatching

Used as:

Division I Level One

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10576

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13934&pm=10576

Problem Statement

    In the real estate business, most purchases are made through real estate agents, who typically have specific regions in which they work. Naturally, different agents have different specialties, both geographically and otherwise.



The goal of this problem is to match an interested customer to the most appropriate agent -- the one most likely to provide a successful outcome to the customer. To this end, your task is to develop an algorithm which assigns a score to a number of customer-agent pairings. You should assign higher scores to pairings which are more likely to conclude successfully, with a property being purchased. To develop this algorithm, you will be given a corpus of data from past pairings, along with the outcomes for those pairings. After submitting your algorithm, you will be scored on an independent dataset, using the AUC metric. For this evaluation metric, the exact scores do not matter, only the ordering they impose. Ideally, the ordering will consist of all the negative instances, followed by all the positive ones. To make these predictions, you will be given three pieces of data. The first two will be constant, and contain information about the agents. For the third, you will be given half the data for training, with the remaining half held back for testing. The data is described below:
  1. A partitioning of agents into brokerages. More info and download
  2. The coverage areas of the agents, as a list of agent-zip code pairs. More info and download
  3. The customer-agent pairings, along with information about the customer and property. More info and download
You will be given all three of the above as String[]'s with one element representing one line from the files for download (one record). You will also be given a String[], test representing a number of pairings with unknown outcomes. You are to return a double[] with elements corresponding to elements of test. These will be your scores, upon which you will be evaluated. The elements of test will be the same as the elements of train except that they will lack the final two fields (which give the outcome). Each element will be in CSV Format.

Scoring

If you ranked the test cases perfectly, you would assign all of the successful pairings (those which would have a one in their final field) higher scores than all of the unsuccessful pairings. In this case, your score would be 1.0. If you just returned a random ordering, you would expect to score about 0.5. Another way to think about the scoring is that it is a decreasing function in the number of inversions your ordering has compared to a correct ordering. In other words, every time you rank a bad test case higher than a good test case (give the bad one a higher score) that decreases your score.
 

Definition

    
Class:AgentMatching
Method:evaluate
Parameters:String[], String[], String[], String[]
Returns:double[]
Method signature:double[] evaluate(String[] agents, String[] zips, String[] train, String[] test)
(be sure your method is public)
    
 

Notes

-During the provisional testing, only 10% of the full dataset will be used for scoring. The remaining 40% (50% used for training, 10% for provisional testing) will be used for final testing.
-As the data comes from a real website, it is noisy and may contain missing or incorrect values.
-The time limit for the call to your method is 5 minutes. The memory limit is 1024MB.
-The example test is the same as the provisional test.
-The training data contains 39797 matchings, the example/provisional test set contains 8051, and the final test set contains 31902.
-More information about the AUC metric and ROC curves can be found at Wikipedia.
 

Examples

0)
    
"1"
Returns: "Provisional Test"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

HamiltonPath

Graph Theory, Math



Used in:

SRM 452

Used as:

Division II Level Three

Writer:

rng_58

Testers:

PabloGilberto , connect4 , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10572

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13906&pm=10572

Problem Statement

    There are N cities in a country, numbered 0 to N-1. Each pair of cities is connected by a bidirectional road.

John plans to travel through the country using the following rules:
  • He must start in one city and end in another city after travelling exactly N-1 roads.
  • He must visit each city exactly once.
  • You are given a String[] roads. If the j-th character of the i-th element of roads is 'Y', he must travel the road that connects city i and city j.
For example, if there are three cities, and he wants to travel the road between city 0 and city 1, there are 4 possible paths: 0->1->2, 1->0->2, 2->0->1, 2->1->0. Paths 0->2->1 and 1->2->0 are not allowed because they do not allow him to travel the road between city 0 and city 1.

Return the number of paths he can choose, modulo 1,000,000,007.
 

Definition

    
Class:HamiltonPath
Method:countPaths
Parameters:String[]
Returns:int
Method signature:int countPaths(String[] roads)
(be sure your method is public)
    
 

Constraints

-roads will contain between 2 and 50 elements, inclusive.
-Each element of roads will contain n characters, where n is the number of elements in roads.
-Each character in roads will be 'Y' or 'N'.
-The i-th character in the i-th element of roads will be 'N'.
-The j-th character in the i-th element of roads and the i-th character in the j-th element of roads will be equal.
 

Examples

0)
    
{"NYN",
 "YNN",
 "NNN"}
Returns: 4
The example from the problem statement.
1)
    
{"NYYY",
 "YNNN",
 "YNNN",
 "YNNN"}
Returns: 0
It's impossible to travel all these roads while obeying the other rules.
2)
    
{"NYY",
 "YNY",
 "YYN"}
Returns: 0
This is also impossible.
3)
    
{"NNNNNY",
 "NNNNYN",
 "NNNNYN",
 "NNNNNN",
 "NYYNNN",
 "YNNNNN"}
Returns: 24

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FunctionalEquation

Graph Theory, Math



Used in:

SRM 456

Used as:

Division I Level Three

Writer:

rng_58

Testers:

PabloGilberto , misof , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10570

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13909&pm=10570

Problem Statement

    f is a function from integers to integers. In other words, f is defined over integers, and f(x) is an integer for all integers x. You are given an integer C. f is called C-beautiful if the following equality is satisfied for all integers x:







Return the minimal possible value of the following formula when f is C-beautiful:







Use the following recursive definitions to generate the sequences x and y:
  • x[0] = xzero
  • For all integer i between 1 and N-1, inclusive, x[i] = (x[i-1] * xprod + xadd) % xmod
  • y[0] = yzero
  • For all integer i between 1 and N-1, inclusive, y[i] = (y[i-1] * yprod + yadd) % ymod
 

Definition

    
Class:FunctionalEquation
Method:minAbsSum
Parameters:int, int, int, int, int, int, int, int, int, int
Returns:long
Method signature:long minAbsSum(int C, int N, int xzero, int xprod, int xadd, int xmod, int yzero, int yprod, int yadd, int ymod)
(be sure your method is public)
    
 

Notes

-64-bit integers should be used to generate the sequences x and y to avoid overflow.
 

Constraints

-C will be between 1 and 16, inclusive.
-N will be between 1 and 10,000, inclusive.
-xmod and ymod will each be between 1 and 1,000,000,000, inclusive.
-xzero, xprod and xadd will each be between 0 and xmod - 1, inclusive.
-yzero, yprod and yadd will each be between 0 and ymod - 1, inclusive.
 

Examples

0)
    
3
10
0
1
1
456
1
1
1
456
Returns: 0
f(x) = x + 1 is a 3-beautiful function.

Since x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} and y = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, the sum of |f(x[i]) - y[i]| is 0.
1)
    
4
10
0
1
1
456
1
1
1
456
Returns: 5
x and y are the same as in example 0, but f(x) = x + 1 is not a 4-beautiful function.
2)
    
16
10000
654816386
163457813
165911619
987654321
817645381
871564816
614735118
876543210
Returns: 3150803357206

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AntOnGraph

Graph Theory, Recursion



Used in:

SRM 446

Used as:

Division I Level Two

Writer:

crazyb0y

Testers:

PabloGilberto , ivan_metelsky , Chmel_Tolstiy , MThorn

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10516

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13900&pm=10516

Problem Statement

    

You are given a directed graph with n vertices, labeled 0 to n-1. The edges of the graph contain values, and each time you traverse an edge, the value of that edge gets added to your total score. If the same edge is traversed multiple times, its value gets added every time. Values can be any number between -499 and 499, inclusive. There are no edges that connect a vertex to itself.

There's an ant at vertex 0 and it wants to get to vertex 1. It must do this in an integer number of seconds between 1 and timeLimit, inclusive. The ant must make exactly stepsPerSecond steps each second, where each step consists of moving from its current vertex V to an adjacent vertex W (W is adjacent to V if there's a directed edge from V to W in the graph). The ant's goal is to get the highest score possible.

The graph is given as three String[]s p0, p1 and p2. Concatenate the j-th characters of the i-th elements of p0, p1 and p2 (in that order) to get a 3-digit String S. If S is "000", then there is no edge from vertex i to vertex j. Otherwise, there is an edge from vertex i to vertex j, and its value is A - 500, where A is the integer value of S. For example, if S is "100", then the value is -400, and if S is "999", the value is 499. Return the decimal representation of the highest possible score as a String with no extra leading zeroes. If it is impossible to reach vertex 1 under the given constraints, return "IMPOSSIBLE" (quotes for clarity) instead.

 

Definition

    
Class:AntOnGraph
Method:maximumBonus
Parameters:String[], String[], String[], int, int
Returns:String
Method signature:String maximumBonus(String[] p0, String[] p1, String[] p2, int stepsPerSecond, int timeLimit)
(be sure your method is public)
    
 

Constraints

-p0 will contain between 2 and 50 elements, inclusive.
-p1 and p2 will each contain the same number of elements as p0.
-Each element in p0, p1 and p2 will contain exactly n characters, where n is the number of elements in p0.
-Each character in p0, p1 and p2 will be a digit ('0'-'9').
-The i-th character of the i-th element of p0, p1 and p2 will be '0'.
-stepsPerSecond will be between 1 and 100, inclusive.
-timeLimit will be between 1 and 1000000000 (10^9), inclusive.
 

Examples

0)
    
{"05","50"}
{"00","00"}
{"01","10"}
3
2
Returns: "3"
Here, there are two vertices. There's an edge from vertex 0 to vertex 1 and an edge from vertex 1 to vertex 0. Both edges have a value of 1. The ant must make exactly 3 steps per second, so during the first second, it will make the following moves: 0->1, 1->0, 0->1. The time limit is 2, so there's time for 3 more moves. However, that would place the ant back at vertex 0, so the ant should stop after the first second.
1)
    
{"05","50"}
{"00","00"}
{"01","10"}
2
3
Returns: "IMPOSSIBLE"
This is the same graph as the previous example, but this time, the ant must make exactly 2 steps per second. The ant can therefore never reach vertex 1 because it will always return to vertex 0 after each second.
2)
    
{"0550","0000","0005","5000"}
{"0000","0000","0000","0000"}
{"0110","0000","0001","1000"}
7
9
Returns: "49"
In this case the ant can traverse cycle 0->2->3->0 and earn 3 points. The ant will keep moving along this cycle and finally go to vertex 1 and earn another point. Thus the number of points modulo 3 is 1. Among all multiple of 7 less than or equal to 63, 49 is the biggest one that satisfies the constraints.
3)
    
{"0540","0000","0004","4000"}
{"0090","0000","0009","9000"}
{"0190","0000","0009","9000"}
7
9
Returns: "-5"
This is the same as the previous example, but this time, the score for the cycle is -3.
4)
    
{"079269665406","506042219642","720809987956",
 "315099331918","952306192584","406390344278",
 "999241035142","370785209189","728363760165",
 "019367419000","279718007804","610188263490"}
{"038604914953","804585763146","350629473403",
 "028096403898","575205051686","427800322647",
 "655168017864","582553303278","980402170192",
 "620737714031","686142310509","092421645460"}
{"063231394554","109852259379","740182746422",
 "853015982521","476805512496","898530717993",
 "430534005863","440162807186","132879980431",
 "685312177072","780267345400","959947501200"}
37
1221
Returns: "20992235"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CubePainting

Dynamic Programming, Graph Theory



Used in:

SRM 446

Used as:

Division I Level Three

Writer:

crazyb0y

Testers:

PabloGilberto , ivan_metelsky , Chmel_Tolstiy , MThorn

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10508

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13900&pm=10508

Problem Statement

    

You are given a 3x3x3 cube. Each face of the cube contains a 3x3 grid of nine squares. Some of the squares are painted and the rest are unpainted. Your task is to calculate the number of ways you can cover all the unpainted squares with "cube-cycles".

A cube-cycle is a sequence of 3 or more squares, where each square is "cube-adjacent" to the next square, and the last square is "cube-adjacent" to the first square. All squares in a cube-cycle must be distinct. Two squares are cube-adjacent if they share a common edge. That common edge can be on a face or on an edge of the cube. Each square in the cube has exactly four cube-adjacent squares.

Note that two cube-cycles might be distinct even if they contain the same set of squares. See example 0.

You are given the cube as a String[] containing 54 characters, where each character represents a single square. The String[] will be formatted as a net of the cube, as shown below:

+---+
|   |
+---+---+---+---+
|   |   |   |   |
+---+---+---+---+
|   |
+---+

Painted squares are represented by '*' characters and unpainted squares are represented by '.' characters. You are only allowed to cover unpainted squares with cube-cycles. You are not allowed to cover painted squares. All unpainted squares must be covered, and no two cube-cycles can overlap each other. Return the number of ways you can cover the cube modulo 1,000,000,007.

 

Definition

    
Class:CubePainting
Method:count
Parameters:String[]
Returns:int
Method signature:int count(String[] cube)
(be sure your method is public)
    
 

Constraints

-

cube will contain exactly 9 elements.

-

Elements 0, 1, 2, 6, 7 and 8 of cube will each contain exactly 3 characters.

-

Elements 3, 4 and 5 of cube will each contain exactly 12 characters.

-

All characters in cube will be either '*' or '.'.

 

Examples

0)
    
{"***",
 "***",
 "***",
 "**....******",
 "**....******",
 "**....******",
 "***",
 "***",
 "***"}
Returns: 3
There are two ways to cover it with one cycle and one way with two cycles.



   

1)
    
{"***",
 "***",
 "***",
 "************",
 "............",
 "************",
 "***",
 "***",
 "***"}
Returns: 1
There is only one way to cover a strip.
2)
    
{".*.",
 "***",
 ".*.",
 ".*..*..*..*.",
 "************",
 ".*..*..*..*.",
 ".*.",
 "***",
 ".*."}
Returns: 1
All squares in the corners should be covered. There are eight independent cycles.
3)
    
{"***",
 "***",
 "***",
 "************",
 "************",
 "************",
 "***",
 "***",
 "***"}
Returns: 1
All squares are painted in this case.
4)
    
{"*.*",
 "...",
 "*.*",
 "*.**.**.**.*",
 "............",
 "*.**.**.**.*",
 "*.*",
 "...",
 "*.*"}
Returns: 0
5)
    
{"***",
 "***",
 "***",
 "............",
 "............",
 "............",
 "***",
 "***",
 "***"}
Returns: 40661

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FoldingMaze

Graph Theory



Used in:

TCHS10 Round 3

Used as:

Division I Level Two

Writer:

vexorian

Testers:

PabloGilberto , ivan_metelsky , StevieT

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10478

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14229&pm=10478

Problem Statement

    NOTE: This problem statement contains images that may not display properly if viewed outside of the applet.



Alice loves mazes so much that she spends most of her spare time drawing new mazes on sheets of graph paper. These mazes work as follows. Every cell is either an empty space or a wall. One of the empty cells is the starting cell and one of the other empty cells is the ending cell. To solve the maze, you must draw a path from the starting cell to the ending cell without lifting your pen. From each cell, you are only allowed to move to an empty neighboring cell. Two cells are neighbors if they share a common side.



Alice is so obsessed that she forces her friend Bob to solve her mazes over and over again. Lately, she began cheating by making her mazes unsolvable. However, Bob, being an avid cheater himself, discovered that he could solve those mazes by folding the sheet of paper until the maze became solvable. Alice did not initially like the fact that Bob had thwarted her attempts to make unsolvable mazes, but she eventually figured out that drawing mazes that can only be solved by folding the paper would be far more interesting than drawing unsolvable mazes.



Alice came up with a new method of creating mazes and a new set of rules. She now draws on both sides of the graph paper. The starting cell is always on the front, but the ending cell may be on either side. Bob must put the sheet of paper on a table with the front side facing up. On each move, he must do one of the following:

  • Move to an empty neighboring cell. The rules here are the same as before. He can only move to cells that are currently visible.
  • Fold the paper once. This is only allowed if the paper is not already in a folded state. The folding line must coincide with a vertical line on the graph paper's grid. The fold must not cover the cell in which Bob is currently located. Horizontal, diagonal or any fold operation with a folding line that does not coincide with a vertical grid line are considered illegal.
  • Unfold the paper if it's currently folded. This will return the paper to its initial state. This is only allowed if doing so will not remove the current cell from view.




For example, consider the following case in which we can see both sides of the sheet (the back side depicted is the part of the sheet that would be visible after rotating it 180 degrees about the vertical axis):







In this case, the third vertical line from the left is used as a folding line.





After folding the paper, it is now possible to move from the starting cell to the second cell from the left in the top row. After that, the paper is unfolded.





Then, move one cell to the right and perform another fold.





Notice that you can fold up either the right or left side of the paper as long as you follow all the rules. After the second fold, the ending cell becomes visible, and it is now possible to move there.



Your task is to help Bob cheat by determining the fastest way to solve these mazes. You are given String[]s frontSide and backSide, describing the front and back sides of the paper, respectively. The j-th character of the i-th element of each String[] represents the cell at row i, column j. Empty cells are denoted by '.', walls are denoted by '#', the starting cell is denoted by 'S' and the ending cell is denoted by 'E'. backSide describes what you would see if you flipped the paper over by rotating it 180 degrees about the vertical axis. Return the minimum number of steps required to solve the maze. If it is not possible to solve the maze, return -1 instead.
 

Definition

    
Class:FoldingMaze
Method:solve
Parameters:String[], String[]
Returns:int
Method signature:int solve(String[] frontSide, String[] backSide)
(be sure your method is public)
    
 

Constraints

-frontSide and backSide will contain an equal number of elements h, where h is between 2 and 50, inclusive.
-Each element of frontSide and backSide will contain an equal number of characters w, where w is between 2 and 50, inclusive.
-Each element of frontSide and backSide will contain only '#', '.', 'S' or 'E' as characters.
-Exactly one character in frontSide will be 'S'.
-backSide will not contain any 'S' characters.
-The total number of 'E' characters in frontSide and backSide will be exactly 1.
 

Examples

0)
    
{"...E",
 "....",
 "S..."}
{"####",
 "####",
 "####"}
Returns: 5
The back of the sheet is full of walls. Therefore, it is not advantageous to fold the sheet at all.
1)
    
{"...E",
 "###.",
 "S.#."}
{"....",
 "....",
 "...."}
Returns: 9
We can first fold the right side like this:
...
##.
S..
Then we get to row 0, column 1:
.*.
##.
...
We may now unfold the maze:
.*.E
###.
..#.
Nine steps are required in total.
2)
    
{"....",
 "S.#.",
 "...."}
{"#...",
 "##.E",
 ".#.#"}
Returns: 6
This time the exit is on the back of the sheet.



1) Go to row 0, column 2:
..*.
..#.
....
2) Fold the left side of the sheet:
.*.
E#.
#..
3) Go to the exit.
3)
    
{"....####",
 "#####..#",
 "S#.....#",
 ".#.....#",
 ".####..#",
 "....####"}
{".##..#..",
 "..#..#..",
 "#.#..#.E",
 "#.#..#..",
 "..#..###",
 ".##....#"}
Returns: 20
The solution for this case was detailed in the statement.
4)
    
{"....####",
 "#####..#",
 "S#.....#",
 ".#.....#",
 ".####..#",
 "....####"}
{".#####.#",
 "..####..",
 "#.####.E",
 "#.####..",
 "..######",
 "........"}
Returns: -1
Note that you are not allowed to fold the paper along horizontal lines.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PerfectPermutationHard

Greedy, Simple Math, Simple Search, Iteration



Used in:

SRM 441

Used as:

Division II Level Three

Writer:

giolekva

Testers:

PabloGilberto , lovro , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10469

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13749&pm=10469

Problem Statement

    A permutation A[0], A[1], ..., A[N-1] is a sequence containing each integer between 0 and N-1, inclusive, exactly once. Each permutation A of length N has a corresponding child array B of the same length, where B is defined as follows:
  1. B[0] = 0
  2. B[i] = A[B[i-1]], for every i between 1 and N-1, inclusive.
A permutation is considered perfect if its child array is also a permutation.



Below are given all permutations for N=3 with their child arrays. Note that for two of these permutations ({1, 2, 0} and {2, 0, 1}) the child array is also a permutation, so these two permutations are perfect.
Permutation		Child array
{0, 1, 2}		{0, 0, 0}
{0, 2, 1}		{0, 0, 0}
{1, 0, 2}		{0, 1, 0}
{1, 2, 0}		{0, 1, 2}
{2, 0, 1}		{0, 2, 1}
{2, 1, 0}		{0, 2, 0}
You are given a int[] P containing a permutation of length N. Find a perfect permutation Q of the same length such that the difference between P and Q is as small as possible. The difference between P and Q is the number of indices i for which P[i] and Q[i] are different. If there are several such permutations Q, return the one among them that has the lexicographically smallest child array.
 

Definition

    
Class:PerfectPermutationHard
Method:reorder
Parameters:int[]
Returns:int[]
Method signature:int[] reorder(int[] P)
(be sure your method is public)
    
 

Notes

-int[] A comes before int[] B (with the same length) lexicographically if A has a smaller integer at the first position where the arrays differ.
 

Constraints

-P will contain between 1 and 50 elements, inclusive.
-P will contain each integer between 0 and N-1, inclusive, exactly once, where N is the number of elements in P.
 

Examples

0)
    
{2, 0, 1}
Returns: {2, 0, 1 }
This permutation is already perfect.
1)
    
{4, 0, 5, 2, 1, 3}
Returns: {2, 0, 5, 4, 1, 3 }
Here the smallest possible difference between P and Q is 2. There are 9 possible choices for Q: {2,0,5,4,1,3}, {3,0,5,2,1,4}, {4,0,1,2,5,3}, {4,0,5,1,2,3}, {4,0,5,2,3,1}, {4,2,5,0,1,3}, {4,3,5,2,1,0}, {4,5,0,2,1,3} and {5,0,4,2,1,3}. Among them, {2,0,5,4,1,3} has the lexicographically smallest child array (this array is {0,2,5,3,4,1}).
2)
    
{2, 7, 3, 0, 6, 4, 5, 1}
Returns: {1, 7, 3, 0, 6, 2, 5, 4 }
3)
    
{11, 8, 10, 1, 5, 4, 0, 7, 3, 9, 12, 6, 2}
Returns: {1, 8, 10, 2, 5, 7, 0, 9, 3, 11, 12, 6, 4 }
4)
    
{0, 1, 4, 2, 3, 5}
Returns: {1, 2, 4, 5, 3, 0 }
5)
    
{0, 2, 6, 5, 7, 3, 1, 4}
Returns: {1, 2, 6, 5, 7, 4, 3, 0 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FractalWheels

Graph Theory, Recursion



Used in:

TCO09 Championship

Used as:

Division I Level One

Writer:

eleusive

Testers:

PabloGilberto , Yarin , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10430

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13765&pm=10430

Problem Statement

    An undirected graph is said to be a wheel if there exists a "center" vertex which is adjacent to all other vertices in the graph, and the subgraph induced by taking all other vertices of the graph is precisely a cycle. Additionally, any wheel must have at least 3 vertices in the cycle surrounding the center vertex. The span of a wheel is the degree of the center vertex. For example, the graph below is a wheel with span 4 (the center vertex is colored black).







We define a fractal wheel with depth d and span h as follows: a fractal wheel with depth 0 and span h is simply a wheel with span h.



To obtain a fractal wheel with depth d > 0 and span h, we first take a fractal wheel with depth d-1 and span h. Let V be the set of all vertices at distance d from the center vertex of this fractal wheel. For each vertex u in V, add to the graph a new wheel with span h such that its center vertex is u. Each added wheel must be vertex-disjoint from the other added wheels. The resulting graph is a fractal wheel with depth d and span h, and the center vertex of the resulting fractal wheel is the same as the center vertex of the initial fractal wheel with depth d-1.



For example, the graph below is a fractal wheel with depth 1 and span 4 (note that adding or removing any edges from this graph would result in a graph which is not a fractal wheel):







Given a graph G with N vertices numbered 0 to N-1, inclusive, you must determine if G is a fractal wheel. Concatenate the elements of edges to get a String containing a comma-separated list of edges describing G. Each edge is formatted (quotes for clarity) "u v", which denotes that there is an edge between vertices u and v in G.



If G is not a fractal wheel, then return an empty int[]. Otherwise, return a int[] with two elements: the depth and span of the fractal wheel, respectively.
 

Definition

    
Class:FractalWheels
Method:describeWheel
Parameters:int, String[]
Returns:int[]
Method signature:int[] describeWheel(int N, String[] edges)
(be sure your method is public)
    
 

Notes

-The distance between two vertices in a graph is the length of the shortest path between them (or infinity if there is no path).
-The degree of a vertex v in a graph G is the total number of vertices in G which are adjacent to v.
 

Constraints

-N will be between 2 and 1000, inclusive.
-edges will contain between 1 and 50 elements, inclusive.
-Each element of edges will contain between 0 and 50 characters, inclusive.
-The elements of edges, when concatenated together, will contain a comma-separated list of edges. Let's call the concatenated string E.
-Each edge in E will be formatted "u v" (quotes for clarity), where u and v are integers between 0 and N-1, inclusive, with no extra leading zeroes, and u is strictly less than v.
-All edges in E will be distinct.
-E will contain at least one edge.
 

Examples

0)
    
5
{
"","0 1,0 2,0 3,0 4,",
"1 2,2 3,3 4,1 4"
}
Returns: {0, 4 }
The first graph from the problem statement.
1)
    
21
{
"0 1,0 2,0 3,0 4,1 2,1 4,1 5,1 6,1 7,1 8,2 3,2 9,2 ",
"10,2 11,2 12,3 4,3 13,3 14,3 15,3 16,4 17,4 18,4 1","",
"9,4 20,5 6,5 8,6 7,7 8,9 10,9 12,10 11,11 12,13 14",
",13 16,14 15,15 16,17 18,17 20,18 19,19 20",""
}
Returns: {1, 4 }
The second graph from the problem statement.
2)
    
13
{
"0 1,0 2,0 3,1 2,1 3,1 4,1 5,1 6,2 3,2 7,2 8,2 9,3 ",
"10,3 11,3 12,4 5,4 6,5 6,7 8,7 9,8 9,10 11,10 12,1",
"1 12,0 7"
}
Returns: { }
Here we have a fractal wheel with depth 1 and span 3, but with an extra edge from the center vertex to an outer-layer vertex.
3)
    
11
{
"0 2,0 3,0 4,0 5,0 6,0 7,0 8,0 9,0 10,1 2,1 10,",
"2 3,3 4,4 5,5 6,6 7,7 8,8 9,9 10"
}
Returns: { }
A fractal wheel with depth 0 and span 10, but with a missing edge that should be incident to the center.
4)
    
3
{
"0 1,1 2"
}
Returns: { }
A fractal wheel must have at least 4 vertices.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WeirdTimes

Dynamic Programming



Used in:

Member SRM 465

Used as:

Division II Level Three

Writer:

boba5551

Testers:

timmac , ivan_metelsky , gojira_tc , vexorian , keshav_57

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10429

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14182&pm=10429

Problem Statement

    

The celebrated general Archibald Waving took charge of the fourth army in the occidental front. After losing the first three armies, Waving has become obsessed with effective synchronization of the army. Whenever Waving needs to write the time at which military operations will be performed, he writes only the minute part of the time (the time also has an hour part, which Waving does not write down). This strategy prevents the enemy from figuring out the exact times of the operations even if he obtains the schedule written by Archibald Waving. Of course, Waving's soldiers are very smart, so they are able to reconstruct the entire schedule from the minute parts alone.



A particular time can be written as AB:CD, where AB represents the hour part, and CD represents the minute part. The schedule is a list of times within the same day, where time can lie in the range from 00:00 to 23:59. Moreover, the times appear in chronological order, i.e. the time of the operation performed earlier should be listed before the time of the operation performed later during the day. Also, no two operations can be performed at the same time.



Waving wants to know if the enemy will be able to figure out anything from the schedule he has written. You are given a int[] minuteValues representing minute parts of the times as written by Waving. An hour assignment can be represented by a int[] whose i-th element is the hour part corresponding to minuteValues[i]. The assignment is considered valid if and only if the schedule obtained from the assignment follows the rules mentioned above. Help Waving by returning the K-th (1-indexed) lexicographically smallest valid hour assignment. If there are less than K valid hour assignments, return a int[] containing single element -1 instead.

 

Definition

    
Class:WeirdTimes
Method:hourValues
Parameters:int[], int
Returns:int[]
Method signature:int[] hourValues(int[] minuteValues, int K)
(be sure your method is public)
    
 

Notes

-int[] X is lexicographically smaller than int[] Y of the same size iff there exists an index i such that X[j] = Y[j], j < i, and X[i] < Y[i].
 

Constraints

-minuteValues will contain between 1 and 50 elements, inclusive.
-Each element of minuteValues will be between 0 and 59, inclusive.
-K will be between 1 and 1,000,000,000, inclusive.
 

Examples

0)
    
{22, 11, 33}
3
Returns: {0, 1, 3 }
The three lexicographically smallest valid hour assignments and the corresponding schedules obtained from them are:
{0, 1, 1} ---> {00:22, 01:11, 01:33}
{0, 1, 2} ---> {00:22, 01:11, 02:33}
{0, 1, 3} ---> {00:22, 01:11, 03:33}
1)
    
{10}
2
Returns: {1 }
All possible schedules in lexicographically sorted order are
00:10, 01:10, 02:10, 03:10, 04:10, 05:10, 06:10, 07:10,
08:10, 09:10, 10:10, 11:10, 12:10, 13:10, 14:10, 15:10, 
16:10, 17:10, 18:10, 19:10, 20:10, 21:10, 22:10, 23:10.
2)
    
{2, 1}
20
Returns: {0, 20 }
3)
    
{1, 2}
20
Returns: {0, 19 }
4)
    
{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 15, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
1
Returns: {-1 }
In the list of minute parts, each next element is less than or equal to the previous one. Operations must follow in chronological order and no two operations can be performed at the same time, so no two listed operations can happen within the same hour. There are 25 elements in the list, but a single day consists of just 24 hours, therefore there are no valid hour assignments.
5)
    
{45, 12, 0, 3, 2, 7, 4, 9, 23, 6, 17, 33}
12345
Returns: {0, 1, 2, 2, 3, 3, 4, 5, 12, 13, 18, 18 }
6)
    
{43, 58}
318
Returns: {-1 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PlanarGraphShop

Dynamic Programming, Graph Theory



Used in:

SRM 453.5

Used as:

Division I Level Two

Writer:

misof

Testers:

PabloGilberto , Yarin , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10412

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14174&pm=10412

Problem Statement

    

In the Kocurkovo village there is a shop that sells simple planar graphs. (See Notes for a definition.)

The cost of any graph with X vertices and Y edges is (X^3 + Y^2) gold coins.

Monika has N gold coins, and she wants to spend all of them on simple planar graphs.

Write a method that gets the value N and computes the minimum number of simple planar graphs Monika has to buy in order to spend exactly N gold coins. She is allowed to buy multiple graphs of the same type.

 

Definition

    
Class:PlanarGraphShop
Method:bestCount
Parameters:int
Returns:int
Method signature:int bestCount(int N)
(be sure your method is public)
    
 

Notes

-A simple graph is an ordered pair (V,E) where V is a finite non-empty set of objects called vertices, and E is a finite set of edges. Each edge is a two-element subset of V.

(You can find drawings of several graphs in Example #3.)
-Note that a simple graph does not contain any loops (edges that connect a vertex to itself) and any duplicate edges. In other words, each edge connects two different vertices, and each pair of vertices is connected by at most one edge.
-A graph is called planar if it has a drawing in the plane such that no two edges intersect.
-Note that a simple planar graph does not have to be connected.
 

Constraints

-N will be between 1 and 50,000, inclusive.
 

Examples

0)
    
36
Returns: 1
For 36 gold coins she can buy a triangle: a simple planar graph with 3 vertices and 3 edges.
1)
    
7
Returns: 7
The only simple planar graph that costs 7 gold coins or less is the graph that consists of a single vertex (and no edges). This graph costs 1^3 + 0^2 = 1, so Monika has to buy 7 of them.
2)
    
72
Returns: 2
She can buy 2 triangles for 36 gold coins each. No simple planar graph costs exactly 72 gold coins, hence the optimal answer in this case is 2.
3)
    
46
Returns: 3

All the graphs Monika can afford are shown in the following picture:

One optimal solution is to buy graphs worth 1 + 9 + 36 gold coins.


This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

KingdomMap

Dynamic Programming, Graph Theory



Used in:

SRM 439

Used as:

Division I Level Three

Writer:

it4.kp

Testers:

PabloGilberto , Andrew_Lazarev , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10384

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13747&pm=10384

Problem Statement

    The king of Byteland always gets confused when he sees maps of his own kingdom because roads often intersect with each other. So, he issued an order to create a new map. He wants the map to contain two vertical columns, each containing a list of towns. Each town in the kingdom must appear exactly once in the map. Each road in the map must be a straight line segment connecting a town from one column to a town in the other column. No two roads are allowed to intersect each other, except at their endpoints if they share a town.



Your task is to create this new map. You are given an int n, the number of towns in the kingdom (numbered 0 to n-1), and a String[] roads. Concatenate the elements of roads to get a String containing a comma-separated list of roads. Each road is formatted "u v" (quotes for clarity), where u and v are the numbers of the towns connected by that road. Roads are bidirectional, and there are no cycles. If it is impossible to draw the map so that it contains all of the original roads, you can choose to exclude some of the roads. You must exclude the minimum possible number of roads necessary to create a valid map. Return a int[] containing the numbers of the excluded roads (the roads are numbered starting from 0 in the same order as they appear in the concatenated String). If there are multiple solutions, return the one that comes first lexicographically.
 

Definition

    
Class:KingdomMap
Method:getRoadsToRemove
Parameters:int, String[]
Returns:int[]
Method signature:int[] getRoadsToRemove(int n, String[] roads)
(be sure your method is public)
    
 

Notes

-int[] A comes before int[] B lexicographically if and only if A contains a smaller number at the first position where they differ.
-A cycle is a sequence of cities that contains at least 3 cities and starts and ends in the same city. Each two cities that are consecutive in the sequence must be connected by a road and all these roads must be distinct.
 

Constraints

-n will be between 1 and 300, inclusive.
-roads will contain between 0 and 50 elements, inclusive.
-Each element of roads will contain between 1 and 50 characters, inclusive.
-The elements of roads, when concatenated together, will contain a comma-separated list of roads. Let's call the concatenated string R.
-R will contain between 0 and n-1 roads, inclusive.
-Each road in R will be formatted "u v" (quotes for clarity), where u and v are integers between 0 and n-1, inclusive, with no extra leading zeroes, and u is less than v.
-All roads in R will be distinct.
-There will be no cycles in the corresponding graph.
 

Examples

0)
    
5
{"0 1,1 2,2 3"}
Returns: { }
There is no need to exclude any roads.
1)
    
7
{"0 1,1 2,2 3,3 4,5 6,2 5"}
Returns: {0 }
In this case, we can draw a valid map after excluding any single road. Since we need the lexicographically smallest answer, we exclude the first road in the list, which has the number 0.
2)
    
20
{"8 17,9 12,4 7,2 7,2 19,3 12,6 12,1 9,5 18,0 12,6 1", "6,0 11,3 14,10 15,12 13,13 18,13 19,15 17,15 19"}
Returns: {1, 3, 5, 14 }
Note that you need to concatenate all elements of roads. When concatenating elements, don't put anything between them. In this case the town "16" in the road "6 16" was cut in half between two elements of roads.
3)
    
1
{}
Returns: { }
roads can be empty.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ErdosNumber

Graph Theory, String Manipulation, String Parsing



Used in:

Member Beta

Used as:

Division I Level One , Division II Level Two

Writer:

Nickolas

Testers:

Rustyoldman , timmac , StevieT , vexorian

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10377

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13935&pm=10377

Problem Statement

    The Erdos number is a way of describing the "collaborative distance" between a scientist and Paul Erdos by authorship of scientific publications.

Paul Erdos is the only person who has an Erdos number equal to zero. To be assigned a finite Erdos number, a scientist must publish a paper in co-authorship with a scientist with a finite Erdos number. The Erdos number of a scientist is the lowest Erdos number of his coauthors + 1. The order of publications and numbers assignment doesn't matter, i.e., after each publication the list of assigned numbers is updated accordingly.

You will be given a String[] publications, each element of which describes the list of authors of a single publication and is formatted as "AUTHOR_1 AUTHOR_2 ... AUTHOR_N" (quotes for clarity only). Paul Erdos will be given as "ERDOS".

Return the list of Erdos numbers which will be assigned to the authors of the listed publications. Each element of your return should be formatted as "AUTHOR NUMBER" if AUTHOR can be assigned a finite Erdos number, and just "AUTHOR" otherwise. The authors in your return must be ordered lexicographically.
 

Definition

    
Class:ErdosNumber
Method:calculateNumbers
Parameters:String[]
Returns:String[]
Method signature:String[] calculateNumbers(String[] publications)
(be sure your method is public)
    
 

Notes

-All authors mentioned in the list must be present in your return.
-Assume that all publications of mentioned authors are given in publications.
-String S is lexicographically before string T if S is a proper prefix of T, or if S has an earlier character at the first position where the strings differ.
 

Constraints

-publications will contain between 1 and 50 elements, inclusive.
-Each element of publications will contain between 1 and 50 characters, inclusive.
-An author is a string of between 1 and 50 uppercase letters ('A'-'Z'), inclusive.
-Each element of publications will be a list of authors, separated by single spaces.
-Each element of publications will not have any trailing spaces.
-The authors in each element of publication will be distinct.
-There will be at most 100 distinct authors in all publications.
-Paul Erdos will be given as "ERDOS", and at least one publication will list him as one of the authors.
 

Examples

0)
    
{"ERDOS"}
Returns: {"ERDOS 0" }
The only author is Erdos himself, with Erdos number equal to 0.
1)
    
{"KLEITMAN LANDER", "ERDOS KLEITMAN"}
Returns: {"ERDOS 0", "KLEITMAN 1", "LANDER 2" }
publications[1] defines Kleitman's number as 1, and publications[0] defines Lander's number as 2.
2)
    
{"ERDOS A", "A B", "B AA C"}
Returns: {"A 1", "AA 3", "B 2", "C 3", "ERDOS 0" }
3)
    
{"ERDOS B", "A B C", "B A E", "D F"}
Returns: {"A 2", "B 1", "C 2", "D", "E 2", "ERDOS 0", "F" }
E has coauthors B (Erdos number 1) and A (Erdos number 2), so his Erdos number is defined through the coauthor with the lowest Erdos number. D and F aren't connected to Erdos and thus have no numbers assigned.
4)
    
{"ERDOS KLEITMAN", "CHUNG GODDARD KLEITMAN WAYNE", "WAYNE GODDARD KLEITMAN", 
 "ALON KLEITMAN", "DEAN GODDARD WAYNE KLEITMAN STURTEVANT"}
Returns: 
{"ALON 2",
"CHUNG 2",
"DEAN 2",
"ERDOS 0",
"GODDARD 2",
"KLEITMAN 1",
"STURTEVANT 2",
"WAYNE 2" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

StrangeCountry

Graph Theory, Greedy



Used in:

SRM 441

Used as:

Division I Level Two

Writer:

giolekva

Testers:

PabloGilberto , lovro , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10375

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13749&pm=10375

Problem Statement

    There is a country with N cities, some of which are connected with bidirectional roads. Your task is to reconfigure the roads so that it is possible to get from each city to every other city. You must do this using the minimum possible number of transformations, where each transformation consists of the following steps:
  1. Choose four different cities A, B, C and D, where roads (A, B) and (C, D) exist, but (A, C), (A, D), (B, C) and (B, D) do not exist.
  2. Destroy roads (A, B) and (C, D).
  3. Build two new roads - either (A, C) and (B, D), or (A, D) and (B, C).
The following images show an example of this transformation. From the first situation you can get the second one or the third one:

  



You are given a String[] g, where the j-th character of the i-th element is 'Y' if there is a road between cities i and j, and 'N' otherwise. Return minimal number of transformations required to accomplish your task, or return -1 if it is impossible.
 

Definition

    
Class:StrangeCountry
Method:transform
Parameters:String[]
Returns:int
Method signature:int transform(String[] g)
(be sure your method is public)
    
 

Constraints

-g will contain between 2 and 50 elements, inclusive.
-Each element of g will contain exactly N characters 'Y' or 'N', where N is the number of elements in g.
-For each i and j, g[i][j] will be equal to g[j][i].
-For each i, g[i][i] will be equal to 'N'.
 

Examples

0)
    
{"NY",
 "YN"}
Returns: 0
This country is already connected.
1)
    
{"NYYNN",
 "YNYNN",
 "YYNNN",
 "NNNNY",
 "NNNYN"}
Returns: 1
 
2)
    
{"NYYNNNN",
 "YNYNNNN",
 "YYNNNNN",
 "NNNNYYN",
 "NNNYNYY",
 "NNNYYNY",
 "NNNNYYN"}
Returns: 1
3)
    
{"NYNYNNNNNNNN",
 "YNYNNNNNNNNN",
 "NYNYYNNNNNNN",
 "YNYNNNNNNNNN",
 "NNYNNYYNNNNN",
 "NNNNYNYNNNNN",
 "NNNNYYNNNNNN",
 "NNNNNNNNYYNN",
 "NNNNNNNYNYNN",
 "NNNNNNNYYNNN",
 "NNNNNNNNNNNY",
 "NNNNNNNNNNYN"}
Returns: 2
4)
    
{"NYNNNN",
 "YNYNNN",
 "NYNYNN",
 "NNYNNN",
 "NNNNNY",
 "NNNNYN"}
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FriendScore

Graph Theory



Used in:

SRM 436

Used as:

Division II Level One

Writer:

Gluk

Testers:

PabloGilberto , ivan_metelsky , ged , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10343

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13698&pm=10343

Problem Statement

    You want to determine the most popular person in a social network. To do this, you will count the number of "2-friends" that each person has. Person A is called a 2-friend of another person B if they are friends with each other or if there exists some person C who is a friend of both A and B. The most popular person is the person with the highest number of 2-friends. (There might be more than one if multiple people all have the maximal number of 2-friends.)

You are given a String[] friends, where the j-th character of the i-th element is 'Y' if person i and person j are friends, and 'N' otherwise. Return the number of 2-friends of the most popular person in this social network.
 

Definition

    
Class:FriendScore
Method:highestScore
Parameters:String[]
Returns:int
Method signature:int highestScore(String[] friends)
(be sure your method is public)
    
 

Constraints

-friends will contain between 1 and 50 elements, inclusive.

-Each element of friends will contain exactly N characters 'Y' or 'N', where N is the number of elements in friends.

-For each i and j, friends[i][j] will be equal to friends[j][i].

-For each i, friends[i][i] will be equal to 'N'.

 

Examples

0)
    
{"NNN",
 "NNN",
 "NNN"}
Returns: 0
Here, there are 3 people and none of them are friends, so everybody has zero 2-friends.
1)
    
{"NYY",
 "YNY",
 "YYN"}
Returns: 2
Each person has two 2-friends.
2)
    
{"NYNNN",
 "YNYNN", 
 "NYNYN", 
 "NNYNY", 
 "NNNYN"}
Returns: 4
Persons 0 and 4 have two 2-friends, persons 1 and 3 have three 2-friends. Person 2 is the most popular one - four 2-friends.
3)
    
{"NNNNYNNNNN",
 "NNNNYNYYNN",
 "NNNYYYNNNN",
 "NNYNNNNNNN",
 "YYYNNNNNNY",
 "NNYNNNNNYN",
 "NYNNNNNYNN",
 "NYNNNNYNNN",
 "NNNNNYNNNN",
 "NNNNYNNNNN"}
Returns: 8
4)
    
{"NNNNNNNNNNNNNNY",
 "NNNNNNNNNNNNNNN",
 "NNNNNNNYNNNNNNN",
 "NNNNNNNYNNNNNNY",
 "NNNNNNNNNNNNNNY",
 "NNNNNNNNYNNNNNN",
 "NNNNNNNNNNNNNNN",
 "NNYYNNNNNNNNNNN",
 "NNNNNYNNNNNYNNN",
 "NNNNNNNNNNNNNNY",
 "NNNNNNNNNNNNNNN",
 "NNNNNNNNYNNNNNN",
 "NNNNNNNNNNNNNNN",
 "NNNNNNNNNNNNNNN",
 "YNNYYNNNNYNNNNN"}
Returns: 6

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DoNotTurn

Graph Theory



Used in:

SRM 436

Used as:

Division I Level Two

Writer:

Gluk

Testers:

PabloGilberto , ivan_metelsky , ged , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10337

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13698&pm=10337

Problem Statement

    There is a NxN maze where each cell contains either a wall or empty space. You are currently in the top-left cell at coordinates (0, 0) and your goal is to reach the bottom-right cell at coordinates (N-1, N-1) making as few turns as possible. You can choose any of the four cardinal directions as your starting direction. Then, from each cell, you can either move forward one cell in your current direction or turn left or right by 90 degrees. You can only walk into empty cells, not walls.

You are given ints M, X0, Y0, A, B, C and D. Generate lists X and Y, each of length M, using the following recursive definitions:

X[0] = X0 MOD P

X[i] = (X[i-1]*A+B) MOD P (note that X[i-1]*A+B may overflow a 32-bit integer)

Y[0] = Y0 MOD P

Y[i] = (Y[i-1]*C+D) MOD P (note that Y[i-1]*C+D may overflow a 32-bit integer)

Cell (x, y) of the maze contains a wall if and only if it is neither the top-left cell nor the bottom-right cell and there exists a value of i between 0 and M-1, inclusive, such that x=X[i] MOD N and y=Y[i] MOD N. Return the minimum number of turns you must make to reach the bottom-right cell of this maze, or return -1 if it is impossible.
 

Definition

    
Class:DoNotTurn
Method:minimumTurns
Parameters:int, int, int, int, int, int, int, int, int
Returns:int
Method signature:int minimumTurns(int N, int X0, int A, int B, int Y0, int C, int D, int P, int M)
(be sure your method is public)
    
 

Notes

-In the statement, "A MOD B" represents the remainder of integer division of A by B. For example, 14 MOD 5 = 4 and 20 MOD 4 = 0.
-The author's solution does not depend on any properties of the pseudorandom generator. It would solve any input of allowed size within the given limits.
 

Constraints

-N will be between 2 and 500, inclusive.

-M will be between 0 and 1,000,000, inclusive.

-X0, Y0, A, B, C and D will each be between 0 and 1,000,000, inclusive.

-P will be between 1 and 1,000,000, inclusive.
 

Examples

0)
    
2
0
0
1
0
0
1
10
2
Returns: 1
There are no walls, so you will have to make only one turn.
1)
    
3
0
1
1
1
1
0
3
3
Returns: -1

The maze in this case looks as follows ('#' denotes a wall, '.' denotes an empty cell):

.#.
.#.
.#.

The target is unreachable.

2)
    
3
0
1
1
1
1
1
3
3
Returns: 3

The maze in this case looks as follows ('#' denotes a wall, '.' denotes an empty cell):

.#.
..#
#..

There is only one possible path and it requires 3 turns.

3)
    
10
911111
845499
866249
688029
742197
312197
384409
40
Returns: 12

The maze and the optimal path in it are given below ('#' denotes a wall, '.' denotes an empty cell, the path is illustrated using 'p' characters):

pp##..#..#
#pp..###..
.#p#.....#
##p...#.#.
.#p.##.#..
##p##.#...
#pp####...
pp#.#...#.
p#pppp#...
ppp##ppppp
4)
    
5
23
2
3
35
5
7
9
3
Returns: 2

The maze in this case looks as follows ('#' denotes a wall, '.' denotes an empty cell):

...#.
.....
...#.
.....
..#..
5)
    
2
0
0
0
0
0
0
1
0
Returns: 1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MismatchedStrings

Dynamic Programming



Used in:

TCO09 Qual 3

Used as:

Division I Level Three

Writer:

misof

Testers:

PabloGilberto , vorthys , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10326

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13758&pm=10326

Problem Statement

    

Well-parenthesized strings are defined using the following rules:

  • The empty string is well-parenthesized.
  • If S is a well-parenthesized string, then (S) is a well-parenthesized string.
  • If S and T are well-parenthesized strings, then ST is a well-parenthesized string.
  • Every well-parenthesized string can be created using the previous rules only.

In this problem we will deal with the complement of this set of strings: The strings that consist only of the characters '(' and ')', but are not well-parenthesized. We will call these strings mismatched.

You are given an int N and a long K. All mismatched strings of length N can be ordered lexicographically, and numbered sequentially, starting with zero. Return the string that will get the number K in this order. If there is no such string, return the empty string instead.

 

Definition

    
Class:MismatchedStrings
Method:getString
Parameters:int, long
Returns:String
Method signature:String getString(int N, long K)
(be sure your method is public)
    
 

Notes

-Given two different strings S and T of equal length, S is lexicographically smaller than T if it has a smaller character at the first position where they differ.
-The ASCII value of '(' is less than the ASCII value of ')'.
 

Constraints

-N will be between 1 and 50, inclusive.
-K will be between 0 and 2^N - 1, inclusive.
 

Examples

0)
    
4
0
Returns: "(((("
For any length, the lexicographically smallest mismatched string consists of '(' characters only.
1)
    
4
4
Returns: "())("
There are 14 mismatched strings of length 4. The first five are "((((", "((()", "(()(", "()((", and "())(". Note that we use a 0-based index, hence K=4 corresponds to the fifth mismatched string.
2)
    
6
63
Returns: ""
There are less than 64 mismatched strings of length 6.
3)
    
7
13
Returns: "((())()"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ConnectingAirports

Graph Theory, Greedy



Used in:

TCO09 Round 2

Used as:

Division I Level Three

Writer:

misof

Testers:

PabloGilberto , marian , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10325

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13760&pm=10325

Problem Statement

    

In the kingdom of Absurdistan there are N airports, and in the far away country of Utopia there are M airports. Currently, there is no air traffic on any of these airports. Each airport has some capacity - i.e., a limit on the number of flights it can handle. Capacities may be different for different airports.

The citizens of the two countries would like to connect them by new flights. The schedule must follow these rules:

  • Each flight is a two-way service that directly connects an airport in Absurdistan and an airport in Utopia.
  • No pair of airports can be connected by more than one flight.
  • Together, the flights must exactly meet the capacities of all airports. That is, for each airport the number of flights scheduled from it to another airports must be exactly the same as the capacity for this airport.
  • If there are multiple schedules that satisfy the previous rules, the lexicographically smallest one (definition follows) must be chosen.

Each possible schedule can be represented as a matrix with N rows and M columns. The rows correspond to airports in Absurdistan (in alphabetical order), the columns to airports in Utopia (again, in alphabetical order). The cell at (r,c) contains the number 1 if the two airports are connected by a flight and 0 otherwise.

To compare two schedules, find the first row in which they differ, and in that row find the first column in which they differ. The one that contains a zero in this cell is lexicographically smaller.

You are given two int[]s: capacityA and capacityU. The int[] capacityA contains the capacities of all the airports in Absurdistan in alphabetical order. The int[] capacityU describes the Utopian airports in the same way. If there is no valid schedule, return an empty String[]. Otherwise, find the lexicographically smallest valid schedule and return it formatted as a String[].

 

Definition

    
Class:ConnectingAirports
Method:getSchedule
Parameters:int[], int[]
Returns:String[]
Method signature:String[] getSchedule(int[] capacityA, int[] capacityU)
(be sure your method is public)
    
 

Notes

-The exact formatting of the output: A zero-one matrix A with M rows and N columns is encoded as a String[] X with M elements, containing N characters each. Character c in element r is '1' if A(r,c)=1, and it is '0' if A(r,c)=0.
 

Constraints

-capacityA will contain between 1 and 50 elements, inclusive.
-capacityU will contain between 1 and 50 elements, inclusive.
-Each element in capacityA will be between 0 and 50, inclusive.
-Each element in capacityU will be between 0 and 50, inclusive.
 

Examples

0)
    
{1,2,3}
{3,1,2}
Returns: {"100", "101", "111" }
In this case there is only one way to schedule the flights.
1)
    
{3,2,1,1}
{1,3,1,2}
Returns: {"0111", "0101", "0100", "1000" }
In this case there are multiple valid schedules. Make sure that you output the lexicographically smallest one.
2)
    
{1,2,3,4}
{5,6,7,8}
Returns: { }
The capacities of airports in Absurdistan are too small.
3)
    
{47,47}
{47,40,7}
Returns: { }
Each pair of airports can only be connected by a single flight.
4)
    
{5,5}
{1,1,2,1,1,1,1,1,1}
Returns: {"001001111", "111110000" }
5)
    
{0,0,0,0}
{0,0,0,0,0,0}
Returns: {"000000", "000000", "000000", "000000" }
Zeros may occur in the input.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ReliefMap

Simulation



Used in:

Marathon Match 50

Used as:

Division I Level One

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10322

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13710&pm=10322

Problem Statement

    *TCO competitors must not submit solutions to MM 50. Doing so may result in disqualification.*

A cartographic agency hired you for a project which involves reconstruction of elevation map of the area from its contour map. A contour map is a kind of topographic map that portrays the relief of the area using contour lines which connect points of approximately equal elevation.

As you start working, you find that the map you are given has no notes regarding the values of elevations or the contour interval (the difference in elevation between successive contour lines) of the map. To restore this information, you can request re-measuring of elevations in certain points of the area, but it is quite expensive, and you want to use as few measurements as possible.

Your task is to reconstruct the elevation map of the area.

Elevation Map Generation

The elevation map is a rectangular array of doubles with W columns and H rows, each element representing the elevation of the corresponding cell above a certain zero level. To generate the elevation map, a number of basic points of the relief is chosen between 15 and 25, inclusive. For each basic point the following parameters are chosen:
  • x-coordinate in [0, W-1],
  • y-cordinate in [0, H-1],
  • elevation z in [0, 99],
  • coefficients f in [100, 199] and w in [0.3, 0.8) (all parameters except for w are integer).
The elevation of a cell (x,y) is calculated as a weighted average of elevations of basic points, with (sqrt((x-xi)2+(y-yi)2) + fi)-wi used as weight for basic point i. Finally, the elevations are scaled: elevation z is replaced with 100*(z-zmin)/(zmax-zmin), where zmax and zmin are the maximal and minimal elevations before scaling.

Contour Map Generation

The contour map is a rectangular array of '0' and '1' characters (represented with String[]) with W columns and H rows, each element representing black ('1') or white ('0') cell.

To generate the contour map, the contour interval D is chosen between 2.0 and 10.0. Initially all cells of the map are white. For each integer multiple z=D, 2*D, 3*D, ..., we can divide the map into two parts: the cells with elevation less than z and the cells with elevation greater than z. Each cell which has elevation greater than z and has a cell with elevation less than z in its Moore neighborhood is marked as being part of a contour line and painted black.

Each local strict extremum (a cell which is strictly higher or lower than all 8 cells of its Moore neighborhood) is marked by painting the cell of the extremum black and the 4 cells which have a common side with it.

Implementation Details

Your code should implement one method getMap(String[] contourMap). Parameter contourMap gives you the contour map of the area, contourMap[y][x] being '1' if the cell at row y and column x was marked as part of a contour line or an extremum, and '0' otherwise.

You can call the library function Relief.measure(x, y) which returns the elevation of the cell at column x and row y plus a random value sampled from standard normal distribution. If adding the random value pushes the elevation below 0 or over 100, it will be adjusted to 0 or 100. Note that for each measurement a new random value is used. You can do at most floor(sqrt(W*H)) measurements. Measuring elevation in a cell outside of the area stops the simulation and results in 0 score for the test case.

You must return your guess for the elevation map of the area as a double[]. The return must contain exactly W*H elements, with element y*W+x representing the elevation in the cell at row y and column x.

Scoring

Your score for a test case will be 100-M/floor(sqrt(W*H))/ERR, where M is the number of measurements done, W and H are x- and y-sizes of the area, and ERR is the average squared error of your guess (calculated as sum of square(z[y][x]-ret[y*W+x]) over all cells of the area divided by W*H). Invalid return of any kind will result in zero absolute score for that test case.

Your overall score will be the sum of YOUR/MAX over all test cases, where YOUR is your score and MAX is the maximal score achieved by anyone on that test case.

Visualizer

A visualizer is avaliable for offline testing.
 

Definition

    
Class:ReliefMap
Method:getMap
Parameters:String[]
Returns:double[]
Method signature:double[] getMap(String[] contourMap)
(be sure your method is public)
    
 

Notes

-All variables (except for the noise in elevation measurements) are chosen uniformly and randomly.
-For more details on the test case generation and scoring implementation see the visualizer source.
-The memory limit is 1024 MB and the time limit is 10 seconds (which includes only time spent in your code).
-There are 10 example test cases and 100 full submission test cases.
 

Constraints

-W and H will be between 50 and 500, inclusive.
 

Examples

0)
    
"1"
Returns: "seed = 1
W = 440
H = 377
"
1)
    
"2"
Returns: "seed = 2
W = 195
H = 228
"
2)
    
"3"
Returns: "seed = 3
W = 462
H = 386
"
3)
    
"4"
Returns: "seed = 4
W = 190
H = 102
"
4)
    
"5"
Returns: "seed = 5
W = 71
H = 120
"
5)
    
"6"
Returns: "seed = 6
W = 412
H = 411
"
6)
    
"7"
Returns: "seed = 7
W = 109
H = 218
"
7)
    
"8"
Returns: "seed = 8
W = 427
H = 354
"
8)
    
"9"
Returns: "seed = 9
W = 329
H = 357
"
9)
    
"10"
Returns: "seed = 10
W = 168
H = 270
"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

NumberGraph

Graph Theory, Math



Used in:

TCO09 Round 5

Used as:

Division I Level Three

Writer:

StevieT

Testers:

PabloGilberto , legakis , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10319

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13763&pm=10319

Problem Statement

    Two integers X and Y are joined by a positive integer P if the magnitude of their difference |X-Y| = P. X and Y are joined by a set of integers if they are joined by one of the numbers in that set. You are given a set of positive integers joiningSet, with the property that the number of trailing zeros in the binary representation of each integer in joiningSet is the same. You are also given a set of integers in a String[] graphSet. Concatenate the elements of graphSet to obtain a space-separated list of these integers. Consider the graph G with an edge joining each pair of numbers in graphSet that is joined by joiningSet. Determine the size of the largest subgraph of G, such that no pair of vertices in the subgraph is separated by a distance greater than 2.
 

Definition

    
Class:NumberGraph
Method:largestSet
Parameters:String[], int[]
Returns:int
Method signature:int largestSet(String[] graphSet, int[] joiningSet)
(be sure your method is public)
    
 

Notes

-In this problem, the size of a graph is equal to the number of vertices it contains.
-The distance between two vertices is the length of the shortest path joining them, and can be considered infinite if the vertices are not connected.
-The distance is measured within the taken subgraph, not within the whole graph.
 

Constraints

-graphSet and joiningSet will each contain between 1 and 50 elements, inclusive.
-Each element of joiningSet will be between 1 and 1000000 (10^6), inclusive.
-Each element of graphSet will contain between 1 and 50 characters, inclusive.
-The concatenation of the elements of graphSet will be a single-space-delimited list of integers, formatted without extra leading zeros.
-graphSet will contain between 1 and 80 integers, inclusive.
-Each integer in graphSet will be between 0 and 1000000 (10^6), inclusive.
-The integers within each of graphSet and joiningSet will be distinct.
-The lowest set bit in the binary representation of each element of joiningSet will be the same.
 

Examples

0)
    
{"1 2 3 4 6 9 13 15 16 18 21 26"}
{2,6,10}
Returns: 4
The subgraph induced by {3,9,13,15} is optimal in this case. 3 and 15 are both joined to 9 and 13, so any distance in this subgraph is no greater than 2.
1)
    
{"4 11 12 10 9 6 2 7 1 8 5"}
{3,5,1,7}
Returns: 9
The subgraph induced by {4, 12, 10, 9, 6, 2, 7, 8, 5} is optimal here.
2)
    
{"100 260 164 244 84 340 52 2"
,"12 388 4 308 180 228 484"}
{16,176,208,48,240,80}
Returns: 8
The number "212" has been separated into two parts "2" and "12". Make sure you concatenate the Strings before splitting into numbers.
3)
    
{"10 6 130 162 164 39 73 27 72 167 41"}
{3,63,95,123,57,91,35,137
,135,125,33,121,17,5,31
,45,67,29,157}
Returns: 8
4)
    
{"2136 2108 876 8"
,"6 348 8 1784 1146 1596 608 446 14"
,"64"
," 344 1452 1938 692 376 1482 860 1870"}
{644,844,348,604,1260,516,868,2100,260
,1492,316,1076,268,852,12,1500,4,772
,1108,188,1444,1764,84,1732,532,332
,1588,500,700,1116,252,1060,68,1092
,724,132,484,340,684,1276,28,1788,588}
Returns: 12
5)
    
{"1000000"}
{1}
Returns: 1
6)
    
{"1 2 3 4 5 6 7 8"}
{1}
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheSquareDivTwo

Greedy



Used in:

SRM 457

Used as:

Division II Level One

Writer:

vexorian

Testers:

PabloGilberto , ivan_metelsky , Chmel_Tolstiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10299

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14144&pm=10299

Problem Statement

    John and Brus like puzzles. They have been playing a new game which involves placing checkers on a square board. The board is a grid containing the same number of columns and rows.



The game begins with John placing checkers on specific cells of the board. Then, R[i] is calculated for each row i, where R[i] is the number of checkers in the i-th row. Brus must then move the checkers in such a way that for each column i in the final board, the number of checkers in that column is equal to R[i]. Note that R[i] is calculated for the initial placement of checkers and is not modified afterwards. In a single turn, Brus can move a checker up, down, left or right into an adjacent empty cell. He may use as many turns as necessary to reach the goal.



You are given a String[] board, where the j-th character of the i-th element is uppercase 'C' if the cell at row i, column j contains a checker and '.' otherwise. Return the final placement of checkers using the same format as the input. Since there may be many possible final placements, return the one that comes first lexicographically.
 

Definition

    
Class:TheSquareDivTwo
Method:solve
Parameters:String[]
Returns:String[]
Method signature:String[] solve(String[] board)
(be sure your method is public)
    
 

Notes

-The lexicographically earlier of two String[]s is the one that has the lexicographically earlier String in the first position at which they differ.
-The lexicographically earlier of two Strings is the one that has the earlier character (using ASCII ordering) at the first position at which they differ.
-In ASCII ordering, a dot character '.' comes before 'C'.
 

Constraints

-board will contain exactly n elements, where n is between 1 and 50, inclusive.
-Each element of board will contain exactly n characters.
-Each element of board will contain only uppercase 'C' or '.' .
 

Examples

0)
    
{"..",
 "C."}
Returns: {"..", ".C" }
R[0] is 0. R[1] is 1. The final placement needs to have 0 checkers in the first column and 1 checker in the last column. Brus can move the checker to two different positions in order to accomplish the goal:
..   .C
.C , ..
Note that the first one comes first lexicographically.
1)
    
{"CC",
 ".C"}
Returns: {"C.", "CC" }
CC -> CC -> C.
.C    C.    CC
2)
    
{".C..",
 "CC.C",
 "..C.",
 "CCCC"}
Returns: {"...C", ".C.C", ".C.C", "CCCC" }
3)
    
{"...CCC",
 "...CCC",
 "...CCC",
 "CCC...",
 "CCC...",
 "CCC..."}
Returns: {"......", "......", "......", "CCCCCC", "CCCCCC", "CCCCCC" }
4)
    
{".....C",
 "....CC",
 "...CCC",
 "..CCCC",
 ".CCCCC",
 "CCCCCC"}
Returns: {".....C", "....CC", "...CCC", "..CCCC", ".CCCCC", "CCCCCC" }
No move was necessary in this case.
5)
    
{"C.C..C.C..C..C.",
 "CCC...C..CCC.C.",
 "......CC...CCCC",
 ".C..CC.C.C.C.C.",
 "C....C.C......C",
 ".....C..CCCCC.C",
 "CCC.......CCCCC",
 "..C.C..C.C...C.",
 "CCC....CCC.CC..",
 "CC.CCCC.CCCC...",
 ".C..C.CC.C.CC.C",
 "C.CCCC..CC..C.C",
 ".CCCC.CCCCCC...",
 "..C...C.CCC.CC.",
 "CCCC..CCC.C...."}
Returns: 
{"...............",
"...............",
"...............",
"...............",
"...............",
".........C..C..",
".........C.CC..",
".C....C.CCCCC.C",
".C.C.CC.CCCCCCC",
"CCCC.CC.CCCCCCC",
"CCCC.CCCCCCCCCC",
"CCCCCCCCCCCCCCC",
"CCCCCCCCCCCCCCC",
"CCCCCCCCCCCCCCC",
"CCCCCCCCCCCCCCC" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheSquareDivOne

Graph Theory



Used in:

SRM 457

Used as:

Division I Level Three

Writer:

vexorian

Testers:

PabloGilberto , ivan_metelsky , Chmel_Tolstiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10298

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14144&pm=10298

Problem Statement

    John and Brus like puzzles. They have been playing a new game which involves placing checkers on a square board. The board is a grid containing the same number of columns and rows.



The game begins with John placing checkers on specific cells of the board. Then, R[i] is calculated for each row i, where R[i] is the number of checkers in the i-th row. Brus must then move the checkers in such a way that for each column i in the final board, the number of checkers in that column is equal to R[i]. Note that R[i] is calculated for the initial placement of checkers and is not modified afterwards. In a single turn, Brus can move a checker up, down, left or right into an adjacent empty cell. He must use as few turns as possible to reach the goal.



You are give a String[] board, where the j-th character of the i-th element is uppercase 'C' if the cell at row i, column j contains a checker and '.' otherwise. Return the final placement of checkers using the same format as the input. Since there may be many possible final placements, return the one that comes first lexicographically.
 

Definition

    
Class:TheSquareDivOne
Method:solve
Parameters:String[]
Returns:String[]
Method signature:String[] solve(String[] board)
(be sure your method is public)
    
 

Notes

-The lexicographically earlier of two String[]s is the one that has the lexicographically earlier String in the first position at which they differ.
-The lexicographically earlier of two Strings is the one that has the earlier character (using ASCII ordering) at the first position at which they differ.
-In ASCII ordering, a dot character '.' comes before 'C'.
 

Constraints

-board will contain exactly n elements, where n is between 1 and 18, inclusive.
-Each element of board will contain exactly n characters.
-Each element of board will contain only uppercase 'C' or '.'.
 

Examples

0)
    
{"...",
 "...",
 "C.."}
Returns: {"...", "...", "..C" }
Initially, R[0] = 0, R[1] = 0, R[2] = 1.

There is currently a checker in column 0 which must be moved to column 2. It can be done in two turns.
1)
    
{"CCC",
 ".C.",
 "CCC"}
Returns: {"C.C", "C.C", "CCC" }
CCC    CCC    C.C    C.C
.C. -> ..C -> .CC -> C.C
CCC    CCC    CCC    CCC


The following sequence also takes three turns, but its final placement does not come earlier lexicographically:



CCC    CCC    CCC    CCC
.C. -> C.. -> CC. -> C.C
CCC    CCC    C.C    C.C


2)
    
{"C..",
 ".C.",
 "..C"}
Returns: {"C..", ".C.", "..C" }
No move is necessary.
3)
    
{"C....","CCCCC","...CC",".CC..",".C.C."}
Returns: {".C...", "CCCCC", ".C..C", ".CC..", ".C.C." }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CirclesCountry

Geometry, Graph Theory



Used in:

SRM 443

Used as:

Division I Level One , Division II Level Two

Writer:

gojira_tc

Testers:

PabloGilberto , Yarin , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10297

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13751&pm=10297

Problem Statement

    Circles Country is a country that contains several circular-shaped districts. Some districts may be situated inside other districts, but their borders do not intersect or touch. Qatam is a resident of Circles Country. When he travels between two locations, he always tries to cross the fewest number of district borders as possible because crossing borders is usually a laborious task.



Imagine Circles Country as an infinite plane. You are given int[]s X, Y and R, where (X[i], Y[i]) are the coordinates of the i-th district's center and R[i] is its radius. Qatam is currently at point (x1,y1) and he needs to get to point (x2,y2). Neither of these points lies on a district border. Return the minimal number of district borders he must cross to get to his destination.
 

Definition

    
Class:CirclesCountry
Method:leastBorders
Parameters:int[], int[], int[], int, int, int, int
Returns:int
Method signature:int leastBorders(int[] X, int[] Y, int[] R, int x1, int y1, int x2, int y2)
(be sure your method is public)
    
 

Constraints

-X will contain between 1 and 50 elements, inclusive.
-X, Y and R will each contain the same number of elements.
-Each element of X and Y will be between -1000 and 1000, inclusive.
-Each element of R will be between 1 and 1000, inclusive.
-x1, y1, x2 and y2 will be between -1000 and 1000, inclusive.
-No two circumferences will have common points.
-The points (x1,y1) and (x2,y2) will not lie on any of the circumferences.
 

Examples

0)
    
{0}
{0}
{2}
-5
1
5
1
Returns: 0
1)
    
{0,-6,6}
{0,1,2}
{2,2,2}
-5
1
5
1
Returns: 2
2)
    
{1,-3,2,5,-4,12,12}
{1,-1,2,5,5,1,1}
{8,1,2,1,1,1,2}
-5
1
12
1
Returns: 3
3)
    
{-3,2,2,0,-4,12,12,12}
{-1,2,3,1,5,1,1,1}
{1,3,1,7,1,1,2,3}
2
3
13
2
Returns: 5
4)
    
{-107,-38,140,148,-198,172,-179,148,176,153,-56,-187}
{175,-115,23,-2,-49,-151,-52,42,0,68,109,-174}
{135,42,70,39,89,39,43,150,10,120,16,8}
102
16
19
-108
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MazeWanderingEasy

Graph Theory



Used in:

SRM 440

Used as:

Division II Level Two

Writer:

gojira_tc

Testers:

PabloGilberto , ivan_metelsky , Vasyl[alphacom]

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10288

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13748&pm=10288

Problem Statement

    According to research conducted recently, listening to classical music increases one's mental abilities, while listening to metal decreases them. Now, yet another experiment is being conducted to try to prove or disprove this statement.



In this new experiment, a mouse is placed in a rectangular maze consisting of NxM squares. Each square either contains a wall or is empty. The maze is structured in such a way that for any two empty squares, there exists exactly one path between them. A path is a sequence of pairwise distinct empty squares such that every two consecutive squares are neighboring. Two squares are considered neighboring if they share a common edge.



One of the empty squares in the maze contains a piece of cheese. The mouse's goal is to reach that square without visiting the same square twice. The mouse can only move between neighboring squares. Since the mouse has been listening to classical music for a week, he is extremely intelligent and guaranteed to achieve his goal.



As the mouse moves from his starting point to the cheese, he may encounter some squares where he must choose between several neighboring squares to continue. This happens when the mouse steps into a square which has more than one neighboring empty square, excluding the square from which he came, or when he has more than one neighboring empty square at the start. These situations are called "decisions" and the mouse will always make the right choice.



You are given a String[] maze representing the maze. It contains N elements, each containing M characters. Empty squares are denoted by '.', walls are denoted by uppercase 'X', the mouse's starting point is denoted by 'M', and the square containing the cheese is denoted by '*'. Return the number of decisions the mouse will make on his way to the cheese.
 

Definition

    
Class:MazeWanderingEasy
Method:decisions
Parameters:String[]
Returns:int
Method signature:int decisions(String[] maze)
(be sure your method is public)
    
 

Constraints

-maze will contain between 1 and 50 elements, inclusive.
-Each element of maze will contain between 1 and 50 characters, inclusive.
-Elements of maze will be of the same length.
-maze will contain only '.', 'X', 'M' or '*' characters.
-There will be exactly one '*' character in maze.
-There will be exactly one 'M' character in maze.
-For every pair of empty squares in the maze, there will exist exactly one path between them.
 

Examples

0)
    
{"*.M"}
Returns: 0
From each square, the mouse can only move to one other square, so he never has to make any decisions.
1)
    
{"*.M",
 ".X."}
Returns: 1
The mouse has to make a decision right at the start.
2)
    
{"...",
 "XMX",
 "..*"}
Returns: 2
The mouse makes decisions at both squares before reaching the cheese.
3)
    
{".X.X......X",
 ".X*.X.XXX.X",
 ".XX.X.XM...",
 "......XXXX."}
Returns: 3
4)
    
{"..........*",
 ".XXXXXXXXXX",
 "...........",
 "XXXXXXXXXX.",
 "M.........."}
Returns: 0

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CellRemoval

Graph Theory, Simple Search, Iteration



Used in:

SRM 435

Used as:

Division I Level One , Division II Level Two

Writer:

almelv

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10275

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13697&pm=10275

Problem Statement

    In biology, organisms have the following property: Starting from the first cell (the zygote), each cell during an organism's development process either divides into 2 other cells or does not divide at all. An organism is mature when all of its cells will not divide any further.



Let's assign a unique number to each cell in an organism's development process. For example, consider a species in which each organism starts with cell 0, which divides into cells 1 and 2. Cell 1 divides into cells 3 and 4. Cells 2, 3 and 4 do not divide. Every mature organism of this species will consist of exactly 3 cells - 2, 3 and 4.



During the development process, if we kill a cell, it will be absent in the mature form of the organism. If that cell happens to be a cell that divides, then the mature organism will be missing all of the cell's descendants as well because the cell is killed before it has a chance to divide. For example, in the organism described above, if we kill cell 1 during the development process, the mature organism will contain only cell 2.



You are given a int[] parentCell describing the development process of an organism. The i-th element of parentCell is the parent cell of cell i (where i is a 0-based index). The zygote's parent is -1. Return the number of cells the mature form of this organism would have if you killed cell deletedCell during the development process.
 

Definition

    
Class:CellRemoval
Method:cellsLeft
Parameters:int[], int
Returns:int
Method signature:int cellsLeft(int[] parent, int deletedCell)
(be sure your method is public)
    
 

Constraints

-parentCell will contain exactly N elements, where N is an odd integer between 1 and 50, inclusive.
-There will be exactly one "-1" element in parentCell.
-Every element of parentCell will be between -1 and N-1, inclusive.
-parentCell will form a binary tree.
-deletedCell will be between 0 and N-1, inclusive.
 

Examples

0)
    
{-1,0,0,1,1}
2
Returns: 2
This is the example organism from the problem statement. If we kill cell 2, there will still be two cells left (3 and 4).
1)
    
{-1,0,0,1,1}
1
Returns: 1
This is the example organism from the problem statement. If we kill cell 1, the only cell left will be cell 2. Cells 3 and 4 will not exist because cell 1 is their ancestor.
2)
    
{-1,0,0,1,1}
0
Returns: 0
If we kill the zygote, there is nothing left.
3)
    
{-1,0,0,2,2,4,4,6,6}
4
Returns: 2
4)
    
{26,2,32,36,40,19,43,24,30,13,21,14,24,21,19,4,30,10,44,12,7,32,17,43,
 35,18,7,36,10,16,5,38,35,4,13,-1,16,26,1,12,2,5,18,40,1,17,38,44,14}
24
Returns: 14

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

IncreasingLists

Dynamic Programming, String Manipulation



Used in:

SRM 434

Used as:

Division I Level Three

Writer:

darnley

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10265

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13696&pm=10265

Problem Statement

    

A string is called an increasing list if it is a comma-separated list of increasing positive integers with no leading zeroes. For example, the strings "2,3,9", "30", and "1,100,1000000000000000000000" are increasing lists, while "5,6,6", "1,2,3,", "0" and "1,02" are not.

You're given a String mask consisting of digits, commas and question marks. Replace each question mark with a digit or a comma, so that the resulting string is an increasing list, and return the resulting string. If there are multiple possible resulting strings, return the lexicographically smallest one. If it is impossible to produce an increasing list, return the string "impossible" (quotes for clarity only).

 

Definition

    
Class:IncreasingLists
Method:makeIncreasingList
Parameters:String
Returns:String
Method signature:String makeIncreasingList(String mask)
(be sure your method is public)
    
 

Notes

-A string S is greater than a string T lexicographically if T is a proper prefix of S, or if S has a greater character at the first position where the strings differ.
-Character ',' (comma) is lexicographically smaller than any digit ('0'-'9').
 

Constraints

-mask will contain between 1 and 50 characters, inclusive.
-mask will contain only commas (','), digits ('0'-'9') and question marks ('?').
 

Examples

0)
    
"??"
Returns: "10"
There is no way to place two numbers here, so we need one two-digit number. The lexicographically smallest one is 10.
1)
    
"???"
Returns: "1,2"
This mask stands for either a three-digit number or two one-digit numbers (comma-separated). Since a comma is lexicographically smaller than any digit, "1,2" is lexicographically smaller than "100".
2)
    
"?????????,9"
Returns: "1,2,3,4,5,9"
The lists ends with a 9, so it can contain only one-digit numbers. It is optimal to use the smallest numbers.
3)
    
"??????????,9"
Returns: "impossible"
The lists ends with a 9, so it can contain only one-digit numbers. However, the length of a list of one-digit numbers must be odd.
4)
    
"?,10,?????????????????,16,??"
Returns: "impossible"
There is too much space between 10 and 16, we can only put numbers 11 to 15.
5)
    
"?2?5??7?,??"
Returns: "12,50,70,71"
6)
    
"???????????????????????????????,???"
Returns: "1,10,11,100,101,102,103,104,105,106"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

YetAnotherStonesGame

Dynamic Programming, Graph Theory



Used in:

TCO09 Round 3

Used as:

Division I Level Three

Writer:

StevieT

Testers:

PabloGilberto , Yarin , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10256

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13761&pm=10256

Problem Statement

    

Johnny is playing a simple game with a set of colored stones and a circular board with squares laid out in a track around the edge, some of which are marked. To start with, he places some stones of different colors on the board in different unmarked squares and marks the starting position of each stone. He then picks some number from allowedMoves and advances some stone that number of squares clockwise around the board. If the square that the stone lands in is unmarked, then he leaves the stone there and marks the square. If the square was the starting position of that particular stone, then he removes the stone from the board. Otherwise, if the square had previously been marked, the move is invalid and he returns the stone to its position before he moved it at the beginning of this turn. He then repeats this process. The board is considered complete once all the squares are marked and all the stones have been removed (having moved at least once, then returned to their starting positions). To make the game more interesting, some of the squares on the board are marked before he starts the game and these squares are given in a String markedSquares, in which a marked square is denoted 'X' and an unmarked square '.'. The squares are given in clockwise order. Note that since the board is circular, the first element of markedSquares is adjacent to the last element. Return the minimum number of stones that Johnny would need to place on the board in order to complete the game, or -1 if it is impossible to complete the board.

 

Definition

    
Class:YetAnotherStonesGame
Method:fewestStones
Parameters:int[], String
Returns:int
Method signature:int fewestStones(int[] allowedMoves, String markedSquares)
(be sure your method is public)
    
 

Constraints

-markedSquares will contain between 6 and 50 characters, inclusive.
-Each character in markedSquares will be uppercase 'X' or '.'.
-markedSquares will contain at least 1 '.' character.
-allowedMoves will contain between 1 and 6 elements, inclusive.
-Each element of allowedMoves will be between 1 and 6, inclusive.
-The elements of allowedMoves will be distinct.
 

Examples

0)
    
{4}
"............"
Returns: 4
There is only one move allowed in this case. Any stone will advance once around the board and return to its starting point. 4 stones placed in consecutive squares will therefore complete the board.
1)
    
{4}
"............."
Returns: 1
With the board an extra square long, a single stone will advance 4 times around the board and return to its starting position.
2)
    
{2,3}
"..X..XX.X...XX"
Returns: -1
There is no way to complete this board.
3)
    
{5,3,6}
"....X...X.X.X..........X..X.....XXX....X....XXX"
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LinearPolyominoCovering

Greedy



Used in:

SRM 429

Used as:

Division II Level One

Writer:

darnley

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10251

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13520&pm=10251

Problem Statement

    

You have an infinite number of the following two polyominoes: AAAA and BB.

You are given a String region, filled with characters '.' and 'X'. You need to cover (without overlapping) all the 'X' characters with the given polyominoes.

Return a String that contains the same region with cells marked '.' left untouched, and cells marked 'X' changed to 'A' or 'B', according to the polyomino that covers the cell.

If there is no solution, return the String "impossible" (quotes for clarity only).

If there are multiple solutions, return the lexicographically smallest one.

 

Definition

    
Class:LinearPolyominoCovering
Method:findCovering
Parameters:String
Returns:String
Method signature:String findCovering(String region)
(be sure your method is public)
    
 

Notes

-A string S is greater than a string T lexicographically if T is a proper prefix of S, or if S has a greater character at the first position where the strings differ.
 

Constraints

-region will contain between 1 and 50 characters, inclusive.
-Each character of region will be either '.' or uppercase 'X'.
 

Examples

0)
    
"XXXXXX"
Returns: "AAAABB"
There is only room for one AAAA polyomino, so there are three possible coverings: "AAAABB", "BBAAAA", and "BBBBBB". The first one is the lexicographically smallest.
1)
    
"XX.XX"
Returns: "BB.BB"
The empty cell in the middle should be left uncovered, so we can't use the AAAA polyomino here.
2)
    
"XXXX....XXX.....XX"
Returns: "impossible"
The middle segment of Xs is too narrow for an AAAA polyomino, but is too wide for a BB polyomino.
3)
    
"X"
Returns: "impossible"
4)
    
"XX.XXXXXXXXXX..XXXXXXXX...XXXXXX"
Returns: "BB.AAAAAAAABB..AAAAAAAA...AAAABB"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Telltale

Dynamic Programming, Graph Theory, Search, Simple Search, Iteration, Simulation



Used in:

TCHS SRM 63

Used as:

Division I Level Two

Writer:

DStepanenko

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10205

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13532&pm=10205

Problem Statement

    

Your friend likes to go to parties and tell stories. At each party, he tells his favorite tale. The tale can be told in two variants - true or exaggerated. The exaggerated variant of the story sounds much cooler, so he wants to use it as often as possible, but he doesn't want to be known as a liar. The problem is that some people already know the true variant of this story, so if any of those people are at the same party as him, he must tell the story truthfully. Also, if a person hears different variants of the story at different parties, she's also able to detect that your friend is a liar, so he must avoid this as well.

You are given an int n, the total number of people (numbered 1 through n). The people who already know the true variant of the story are given in the int[] a. The people at each party that your friend will attend are given in the String[] parties, where the i-th element is a space-separated list of all the people attending the i-th party. Return the maximum number of parties where your friend can tell the exaggerated variant of his story and not have anybody detect that he's a liar.

 

Definition

    
Class:Telltale
Method:doNotTellTheTruth
Parameters:int, int[], String[]
Returns:int
Method signature:int doNotTellTheTruth(int n, int[] a, String[] parties)
(be sure your method is public)
    
 

Constraints

-n will be between 1 and 50, inclusive.
-a will contain between 0 and n elements, inclusive.
-Each element of a will be between 1 and n, inclusive.
-All elements of a will be distinct.
-parties will contain between 1 and 50 elements, inclusive.
-Each element of parties will contain between 1 and 50 characters, inclusive.
-Each element of parties will contain a single-space separated list of integers without leading or trailing spaces.
-Integers in each element of parties will be between 1 and n, inclusive, with no leading zeros.
-Integers in each elements of parties will be distinct.
 

Examples

0)
    
4
{}
{"1 2", "3", "2 3 4"}
Returns: 3
Nobody knows the true story, so your friend can tell the exaggerated variant at all 3 parties.
1)
    
4
{1}
{"1 2 3 4"}
Returns: 0
Person 1 knows the true story. There's only one party, and she is present there, so your friend can never tell the exaggerated variant.
2)
    
4
{}
{"1 2 3 4"}
Returns: 1
Now person 1 doesn't know the true story, so your friend can tell the exaggerated variant.
3)
    
4
{1}
{"1", "2", "3", "4", "4 1"}
Returns: 2
Person 1 knows the true story. She's present at parties 0 and 4 (0-indexed), so he must tell the true variant at those parties. Person 4 will hear the true story at party 4, and she will also be at party 3, so he must tell the true variant at party 3. So, the exaggerated variant can only be told at parties 1 and 2.
4)
    
10
{1, 2, 3, 4}
{"1 5", "2 6", "7", "8", "7 8", "9", "10", "3 10", "4"}
Returns: 4
5)
    
8
{1, 2, 7}
{"3 4", "5", "5 6", "6 8", "8"}
Returns: 5
6)
    
3
{3}
{"1", "2", "1 2", "1 2 3"}
Returns: 0

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ThirtyRocks

Greedy, Math, Simple Search, Iteration



Used in:

TCHS SRM 64

Used as:

Division I Level Two

Writer:

vexorian

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10199

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13533&pm=10199

Problem Statement

    

You have 30 rocks and n boxes in which you wish to place them. Each box can hold some minimum and maximum number of rocks. The i-th element of boxMinimum is the minimum number of rocks you can place in box i, and the i-th element of boxMaximum is the maximum number of rocks you can place in box i.



If you can put all 30 rocks into the boxes, return a int[] containing exactly n elements, where the i-th element is the number of rocks in box i. If there are multiple ways to do this, return the one that comes first lexicographically. If it is not possible to put all 30 rocks into boxes, return an empty int[] instead.

 

Definition

    
Class:ThirtyRocks
Method:assign
Parameters:int[], int[]
Returns:int[]
Method signature:int[] assign(int[] boxMinimum, int[] boxMaximum)
(be sure your method is public)
    
 

Notes

-int[] A comes before int[] B lexicographically if A contains the lesser number in the first position in which A and B differ.
 

Constraints

-boxMinimum will contain between 1 and 50 elements, inclusive.
-boxMaximum will contain the same number of elements as boxMinimum.
-Each element of boxMinimum will be between 0 and 30, inclusive.
-Each element i of boxMaximum will be between boxMinimum[i] and 30, inclusive.
 

Examples

0)
    
{0,0}
{20,10}
Returns: {20, 10 }
The only possible way to distribute the 30 rocks is by placing 20 rocks in the first box and the remaining 10 in the second box. If we moved any of the rocks to another box we would be breaking the specified limits.
1)
    
{15,15,15}
{25,24,16}
Returns: { }
This time, there are three boxes but each of them requires a minimum of 15 rocks, which is impossible to achieve since we only have 30.
2)
    
{0,0}
{20,11}
Returns: {19, 11 }
This is similar to the first example. However, we are now allowed to place 11 rocks in the second box. This allows two possible answers: {20,10} and {19,11} . We pick the second one since it comes first lexicographically.
3)
    
{10,0,0}
{10,2,15}
Returns: { }
The first box requires 10 rocks, but you cannot place the remaining rocks in the other boxes since they allow a maximum of 17 rocks. It is not possible to comply with all the rules.
4)
    
{0,0,0,0,0}
{30,30,30,30,30}
Returns: {0, 0, 0, 0, 30 }
Of all the many possible solutions for this case, {0,0,0,0,30} comes first lexicographically.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CommanderIdol

Graph Theory, Simple Math



Used in:

TCHS SRM 64

Used as:

Division I Level Three

Writer:

vexorian

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10197

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13533&pm=10197

Problem Statement

    

You are the commander of a group of soldiers on a battlefield. There are several forts on that battlefield, and you and your soldiers are currently at fort 0. Your task is to send a soldier to each of the other forts to deliver some secret prototypes.



Your mission is considered complete when there is exactly one solider at each of the other forts. You want to complete the mission as soon as possible, but you also want to maintain your high popularity among your soldiers. You have noticed that allowing soldiers to sleep a couple of hours before beginning their missions will make you more popular with them. Specifically, if you let one soldier sleep for X hours before beginning his mission, you will gain X popularity points.



You are given a String[] roads, where the j-th character of the i-th element is '-' if no road exists between forts i and j, or a digit between '0' and '9' representing the number of hours it would take a soldier to travel between forts i and j. Return the maximum total number of popularity points you can gain while still completing the mission as quickly as possible. Return -1 if it is impossible to complete the mission.

 

Definition

    
Class:CommanderIdol
Method:getMaxPopularity
Parameters:String[]
Returns:int
Method signature:int getMaxPopularity(String[] roads)
(be sure your method is public)
    
 

Constraints

-roads will contain n elements, where n is between 2 and 50, inclusive.
-Each element of roads will contain exactly n characters.
-Each character in roads will be '-' or a digit between '0' and '9', inclusive.
-Character i in element i of roads will be '-'.
-Character i in element j of roads will be the same as character j in element i of roads.
 

Examples

0)
    
{"-1-","1-2","-2-"}
Returns: 2
The mission will require at least 3 hours to be finished. You can allow the soldier assigned to fort 1 to sleep 2 more hours without delaying the mission completion.
1)
    
{"-1--","1-2-","-2--","----"}
Returns: -1
There is no way for your soldiers to reach fort 3, so this mission cannot be accomplished.
2)
    
{"--7-6",
 "----8",
 "7--51",
 "--5-7",
 "6817-"}
Returns: 17

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BuildersCountry

Graph Theory



Used in:

SRM 432

Used as:

Division I Level Three

Writer:

nika

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10178

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13694&pm=10178

Problem Statement

    

There's a far away country where only builders live. They have built a number of cities already, and some of them are connected with bidirectional roads. The existing roads are given in the String[] g, where the j-th character of the i-th element is 'Y' if there's a bidirectional road connecting cities i and j, and 'N' otherwise. Each city contains a number of houses, given in the int[] before, where the i-th element is the number of houses in city i. Exactly one builder lives in each house.



The country will go through a two-phase building process. In the first phase, new bidirectional roads will be built so that every pair of cities will be connected by some path. When a road is built between two cities, every builder from both cities will be involved and each builder will be paid roadCost units of money.



In the second phase, new houses will be built. You are given a int[] after, where the i-th element is the number of houses that must exist in city i after this phase is complete. In other words, after[i] - before[i] new houses must be built in city i during this phase. When a house is built, all builders in that city and all its neighboring cities will be involved and each one will be paid houseCost[i] units of money. Two cities are neighboring if they are directly connected by a road. After each house is built, a new builder will immediately live in that house. Houses can be built in any order.



Return the minimal possible cost required to finish both phases of the building process.

 

Definition

    
Class:BuildersCountry
Method:minCost
Parameters:int[], int[], int[], String[], int
Returns:long
Method signature:long minCost(int[] before, int[] after, int[] houseCost, String[] g, int roadCost)
(be sure your method is public)
    
 

Constraints

-before will contain between 1 and 50 elements, inclusive.
-Each element of before will be between 1 and 100000, inclusive.
-after will contain the same number of elements as before.
-The i-th element of after will be between the i-th element of before and 100000, inclusive.
-houseCost will contain the same number of elements as before.
-Each element of houseCost will be between 1 and 100000, inclusive.
-g will contain the same number of elements as before.
-Each element of g will contain exactly n characters, where n is the number of elements in g.
-Each element of g will contain only uppercase letters 'Y' and 'N'.
-The i-th character of the i-th element of g will always be 'N'.
-The i-th character of the j-th element of g will always be equal to the j-th character of the i-th element of g.
-roadCost will be between 1 and 100000, inclusive.
 

Examples

0)
    
{2, 1, 3, 5}
{2, 1, 3, 5}
{4, 5, 3, 2}
{"NNNN", "NNNN", "NNNN", "NNNN"}
1000
Returns: 13000
We can build roads from city 1 to all other cities for a total cost (1+2)*1000 + (1+3)*1000 + (1+5)*1000 = 13000. All houses are already built.
1)
    
{1, 1, 1, 1}
{1, 3, 1, 2}
{8, 5, 3, 2}
{"NYNN", "YNYN", "NYNY", "NNYN"}
100000
Returns: 39
We don't need to add any roads. If we build one house in city 1, we need to pay 5*(1+1+1). After that, build one house in city 3 for a cost of 2*(1+1). Then, build another house in city 1. This time, the cost will be 5*(1+2+1) since 2 workers now live in city 1. The total cost is 15+4+20=39.
2)
    
{9, 11}
{10, 11}
{5, 1}
{"NN", "NN"}
15
Returns: 400
Build one road and build one house.
3)
    
{1}
{1000}
{2}
{"N"}
888
Returns: 999000
Build 999 houses. Total cost is (1+2+...+999)*2 = 999000.
4)
    
{99, 23, 44, 55, 32}
{99, 23, 44, 55, 32}
{39, 32, 11, 23, 89}
{"NYNNN", "YNNNY", "NNNYY", "NNYNY", "NYYYN"}
54
Returns: 0

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BestRoads

Graph Theory, Greedy



Used in:

SRM 424

Used as:

Division II Level Three

Writer:

Gluk

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10172

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13515&pm=10172

Problem Statement

    There are N cities numbered 0 to N-1. The j-th character of the i-th element of roads is 'Y' if there is a bidirectional road between cities i and j, and 'N' otherwise.

The road connecting cities A and B, where A < B, has a higher priority than the road connecting cities C and D, where C < D, if either A < C or (A = C and B < D). A set of roads is a list of one or more roads sorted from highest to lowest priority. A set S1 has a higher priority than set S2 if road S1[i] has a higher priority than road S2[i], where i is the earliest index at which the two sets differ. A set of roads is called connected if there's a path between any pair of cities containing only the roads from this set.

Your task is to find the connected set with the highest priority containing exactly M roads. Return a int[] where the i-th element is the number of roads in that set containing city i as an endpoint. Return an empty int[] if there is no such set.

 

Definition

    
Class:BestRoads
Method:numberOfRoads
Parameters:String[], int
Returns:int[]
Method signature:int[] numberOfRoads(String[] roads, int M)
(be sure your method is public)
    
 

Constraints

-roads will contain between 1 and 50 elements, inclusive.

-M will be between N-1 and 1,000, inclusive, where N is the number of elements in roads.

-Each element of roads will contain exactly N characters 'Y' or 'N', where N is the number of elements in roads.

-For each i and j roads[i][j] will be equal to roads[j][i].

-For each i roads[i][i] will be equal to 'N'.

 

Examples

0)
    
{"NYYYY","YNYYY","YYNYY","YYYNY","YYYYN"}
10
Returns: {4, 4, 4, 4, 4 }
All roads should be selected.
1)
    
{"NYY","YNY","YYN"}
2
Returns: {2, 1, 1 }
The set must contain roads 0-1 and 0-2.
2)
    
{"NYNNY","YNNNY","NNNNN","NNNNY","YYNYN"}
4
Returns: { }
City 2 can not be connected to others.
3)
    
{"NYYNYYYN","YNNNNYYN","YNNNYNNN","NNNNNNYY","YNYNNNNN","YYNNNNYY","YYNYNYNY","NNNYNYYN"}
10
Returns: {5, 3, 2, 2, 2, 2, 3, 1 }
4)
    
{"NNYY","NNYY","YYNN","YYNN"}
5
Returns: { }
There are totally 4 roads, so we can't choose 5 of them.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GraphicalAuthentication

Geometry



Used in:

MM 43

Used as:

Division I Level One

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10147

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13568&pm=10147

Problem Statement

    Your company, worried about increasing number of successful cracks of systems protected with textual passwords, developed a graphical authentication system and claimed it to be absolutely secure.

The system works as follows. First, the user selects M images from a predefined set of K images as his pass-images. When the user wants to log in, the system will display several slightly distorted pass-images of this user along with a greater number of decoy-images, arranged in a 10x10 grid. The decoy-images are chosen at random from the same set of images and distorted as well. The user must recognize his pass-images and click at any point within the convex hull formed by the vertices of the pass-images. To decrease the probability of logging in by randomly clicking, the process is repeated several times with different images displayed, and the user is authenticated only if he passes all attempts successfully.

You want to prove that this system is not as shoulder-surfing-resistant as the developer claims. Your task is: given the information about successful authentication attempts of a user, analyze it and log in as this user using the same system.

Implementation

Your code should implement two methods, as described below:
  • shoulderSurfing(int K, int M, int SZ). This method is called once to give you the total number of images in the set K, the number of user's pass-images M and the size of an individual image SZ. Besides, in this method you can call the library function Spy.successfulLogin() to get information about one user's successful authentication attempt. The information is given as String[], where elements 0 and 1 are column and row indices of the user's click, and the next 10*SZ elements represent the square image displayed to the user: character [i+2][j] is the color of the pixel in row i and column j ('0' for white and '1' for black).
  • loginAttempt(String[] screen). This method is called between 3 and 8 times and models the authentication attempts you have to pass. screen gives you the image displayed to you, character [i][j] being the color of the pixel in row i and column j. You must return your click formatted as int[] { column index, row index }.
Note that the random numbers generator is recreated immediately after the end of shoulderSurfing method, so the calls of loginAttempt don't depend on the number of calls to Spy.successfulLogin.

Test Case Generation

The predefined set of K images is chosen at random from a set of 256 18x18 images. Each individual image is included to the set with a probability of 0.8, and inverted after that with probability 0.5. The number of pass-images M is chosen between 5 and 9, and the pass-images are chosen randomly from the chosen set of K images.

The image displayed to the user is generated in a same way for both user's and your login attempts. The number of pass-images NP is chosen as 3 with probability 0.4, 2 or 4 with probability 0.2 each and 1 or 5 with probability 0.1 each. The pass-images are chosen randomly from the set of all user's pass-images. The number of decoy-images is chosen between (100-NP)/2 and (100-NP). The decoy images are chosen randomly from the set of all not-pass-images. Using the same pass- or decoy-image several times is possible. The chosen pass-images, decoy-images and empty slots (places where no image will be displayed) are shuffled randomly within the 10x10 grid. Finally, the pass-images and decoy-images (but not the empty slots) are distorted: up to 4 random pixels which have at least one vertically, horizontally or diagonally adjacent pixel of other color of each image are inverted.

The user's click for user's login attempts is generated as a random point with integer coordinates within the convex hull of the vertices of pass-images. For the pass-image located at row i and column j of the 10x10 grid, its vertices are (SZ*i,SZ*j), (SZ*i+SZ-1,SZ*j), (SZ*i,SZ*j+SZ-1) and (SZ*i+SZ-1,SZ*j+SZ-1).

Scoring

Your score for a test case will be 1+1/(1+n) if you manage to log in, where n is the number of user's authentication attempts you required for analysis, and 0 if you fail. Your overall score will be the sum of your individual scores.

Visualization

A visualization tool is available.
 

Definition

    
Class:GraphicalAuthentication
Method:shoulderSurfing
Parameters:int, int, int
Returns:int
Method signature:int shoulderSurfing(int K, int M, int SZ)
 
Method:loginAttempt
Parameters:String[]
Returns:int[]
Method signature:int[] loginAttempt(String[] screen)
(be sure your methods are public)
    
 

Notes

-You may call Spy.successfulLogin() at most 100 times.
-You may return any integer from shoulderSurfing, it will be ignored.
-Any kind of invalid return results in a zero score for this test case.
-For more details on the test case generation and simulation implementation see the visualizer source.
-The memory limit is 1024 MB and the time limit is 20 seconds (which includes only time spent in your code).
-The source code size limit is 300KB.
-There are 10 example test cases and 100 full submission test cases.
-The behavior of clicks that occur on the border of the convex hull is undefined and could be either counted or uncounted.
-The final test set will use a different set of images. They will be the same size and have similar characteristics.
 

Examples

0)
    
"1"
Returns: "seed = 1
"
K = 205

M = 5

1)
    
"2"
Returns: "seed = 2
"
K = 223

M = 8

2)
    
"3"
Returns: "seed = 3
"
K = 201

M = 8

3)
    
"4"
Returns: "seed = 4
"
K = 200

M = 5

4)
    
"5"
Returns: "seed = 5
"
K = 206

M = 6

5)
    
"6"
Returns: "seed = 6
"
K = 204

M = 6

6)
    
"7"
Returns: "seed = 7
"
K = 197

M = 9

7)
    
"8"
Returns: "seed = 8
"
K = 197

M = 5

8)
    
"9"
Returns: "seed = 9
"
K = 203

M = 7

9)
    
"10"
Returns: "seed = 10
"
K = 205

M = 5


This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CavePassage

Graph Theory, Search, Simple Math



Used in:

SRM 422

Used as:

Division I Level Two

Writer:

mateuszek

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10123

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13513&pm=10123

Problem Statement

    Several travelers are standing at the entrance of a dark cave. The travelers must all pass through the cave and stand together at the exit. Unfortunately, a variety of circumstances can make it impossible for them to all pass through the cave together at the same time. Therefore, they may have to take turns going through the cave in smaller groups. There is only one map though, and it is impossible to navigate the cave without it, so whenever a group of travelers is inside the cave, one member of that group must be holding the map.



When a group of travelers walks through the cave, either from the entrance or the exit, they must traverse an old bridge to get to the other side of the cave. The entire group inside the cave must cross the bridge together at the same time. The bridge cannot hold more than bridgeStrength kilograms, or it will collapse. You are given a int[] travelersWeights, where the i-th element is the weight of the i-th traveler in kilograms.



Travelers may walk through the cave alone. Although, when travelers walk through the cave in a group of two or more, each traveler must trust at least one of the other travelers in the group. You are given a String[] trustTable, where the j-th character of the i-th element is 'Y' if traveler i trusts traveler j, and 'N' otherwise. Note that the trust relation is not necessarily symmetric.



Travelers walk at different speeds, but when they go through the cave, they must stick together and walk at the same speed. Therefore, when a group of travelers walks through the cave, they must walk at the speed of the slowest traveler in the group. You are given a int[] travelersTimes, where the i-th element is the amount of time it takes the i-th traveler to walk through the cave in any direction.



Return the minimal total time required for all the travelers to end up together at the exit of the cave. If it is impossible, return -1 instead.
 

Definition

    
Class:CavePassage
Method:minimalTime
Parameters:int[], int[], String[], int
Returns:int
Method signature:int minimalTime(int[] travelersWeights, int[] travelersTimes, String[] trustTable, int bridgeStrength)
(be sure your method is public)
    
 

Constraints

-travelersWeights will contain between 1 and 13 elements, inclusive.
-Each element of travelersWeights will be between 1 and 1000, inclusive.
-travelersTimes will contain the same number of elements as travelersWeights.
-Each element of travelersTimes will be between 1 and 1000, inclusive.
-trustTable will contain the same number of elements as travelersWeights.
-Each element of trustTable will contain exactly n characters, where n is the number of elements in trustTable.
-Each element of trustTable will contain only uppercase letters 'Y' and 'N'.
-The i-th character of the i-th element of trustTable will always be 'Y'.
-bridgeStrength will be between 1 and 5000, inclusive.
 

Examples

0)
    
{ 1, 1, 1 }
{ 2, 3, 4 }
{ "YYY", "YYY", "YYY" }
2
Returns: 9
The travelers can achieve the goal as follows. First, traveler 0 and traveler 2 go through the cave together. It normally takes 2 time units for traveler 0 to go through the cave, and it takes 4 time units for traveler 2. Since they are traveling together in a group, they must walk at the speed of the slower traveler. So, after 4 time units, both travelers are at the exit. Then, traveler 0 takes the map and goes back through the cave to the entrance. This time, it only takes 2 time units because he is alone. Finally, traveler 0 and traveler 1 go through the cave together in 3 time units and all the travelers end up together at the exit. The total time is 4 + 2 + 3 = 9.
1)
    
{ 1, 1, 1 }
{ 2, 3, 4 }
{ "YYY", "YYY", "NYY" }
2
Returns: 10
Here things become a little bit more complicated, because traveler 2 doesn't trust traveler 0.
2)
    
{ 1, 1, 1 }
{ 7, 13, 19 }
{ "YYN", "NYY", "YNY" }
3
Returns: 19
3)
    
{ 43 }
{ 23 }
{ "Y" }
42
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CactusCount

Graph Theory, String Parsing



Used in:

SRM 419

Used as:

Division II Level Three

Writer:

andrewzta

Testers:

PabloGilberto , Olexiy , marek.cygan , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10077

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13510&pm=10077

Problem Statement

    

A vertex cactus is a connected undirected graph such that each vertex belongs to at most one simple cycle. A simple cycle is a cycle that doesn't pass through any vertex more than once. For example, the graph pictured below is a vertex cactus:

You are given an int n, the number of vertices in a graph G. The vertices are numbered from 1 to n. The edges in G are given in the String[] edges. Concatenate the elements of edges to get a comma-separated list of integer pairs. The integers in each pair are separated by a space. The pair "i j" (quotes for clarity) means that there is an edge between vertices i and j. Return the number of connected components of G that are vertex cacti.

 

Definition

    
Class:CactusCount
Method:countCacti
Parameters:int, String[]
Returns:int
Method signature:int countCacti(int n, String[] edges)
(be sure your method is public)
    
 

Notes

-A connected component of a graph G is a set of vertices such that each pair of vertices in the set is connected by a path, and no vertex outside the set is connected to any vertex within the set.
 

Constraints

-n will be between 1 and 200, inclusive.
-edges will contain between 0 and 50 elements, inclusive.
-Each element of edges will contain between 1 and 50 characters, inclusive.
-When concatenated, edges will contain a comma separated list of integer pairs.
-The integers within each pair will be separated by a space.
-The integers within each pair will be distinct.
-Each integer will be between 1 and n, inclusive, with no leading zeroes.
-Every pair of vertices will be connected by at most one edge.
 

Examples

0)
    
3
{"1 2,1 3,2 3"}
Returns: 1
One cycle is a vertex cactus.
1)
    
10
{}
Returns: 10
Here each vertex is a component by itself. A graph with one vertex is a vertex cactus.
2)
    
5
{"1 2,3 4,4 5"}
Returns: 2
Both components are trees. A tree is a vertex cactus.
3)
    
17
{"1 2,2 3,3 4,4 5,5 3,1 3,6 7,7 8,6 8,8 9,9 1",
 "0,10 11,11 9,12 13,14 15,15 16,16 17,14 17,14 16"}
Returns: 2
Here are two cacti and two non-cacti. The component with vertices 1, 2, 3, 4 and 5 is not a vertex cactus because vertex 3 belongs to two cycles: 1-2-3 and 3-4-5. The component with vertices 14, 15, 16 and 17 is not a vertex cactus either. Vertex 14, for example, belongs to more than one cycle.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LostSortingAlgorithm

Graph Theory, Sorting, String Manipulation



Used in:

TCHS SRM 57

Used as:

Division I Level Three

Writer:

ltdtl

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10064

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13526&pm=10064

Problem Statement

    Many economists like to represent objects with numbers and compare them using various measures. For example, when shopping for houses, they may represent attributes like cost, number of bedrooms, and distance from work as numbers. They can then prioritize these attributes and easily determine the best match. Consider the following 4 houses:
  • A: $100,000, 2 bedrooms, 30 minutes from work
  • B: $200,000, 3 bedrooms, 10 minutes from work
  • C: $300,000, 3 bedrooms, 10 minutes from work
  • D: $100,000, 3 bedrooms, 20 minutes from work
One way to prioritize the attributes is as follows:

1) The most important attribute is the number of bedrooms. We don't need a big house, so among all the houses, prefer the ones that have less bedrooms.

2) The second most important attribute is the distance to work. Among houses that are tied after step 1, prefer the ones that are closer to work.

3) The least important attribute is cost. Among houses that are still tied after step 2, prefer the ones that cost less.

If we sort the 4 houses above using this prioritization, we get (from most to least preferred): A, B, C, D. House A is preferred over all other houses because it has 2 bedrooms, while B, C and D have 3 bedrooms each. Houses B and C are preferred over house D because they they are closer to work than D. And, finally, house B is preferred over house C because B is cheaper.

Your friend Helen is shopping for houses, but she forgot to bring her prioritized list of attributes. Luckily, she does have a list of houses that were sorted according to that prioritization. She has asked you to help her recover the prioritized list of attributes.

You are given a String[] clues containing the list of houses sorted from most to least preferred. Each element of clues represents one house and contains the values of the attributes for that house. The i-th character (0-indexed) is the value of the i-th attribute, and is a hexadecimal digit ('0'-'9','A'-'F'). Lower values are preferred to higher values for all attributes. You must determine the order in which the attributes were prioritized to produce this list. Assume that after the given list was sorted, there were no ties (meaning no two houses were equally as good according to the prioritization).

Return a String containing the indices (0-indexed) of the prioritized attributes from most to least important. If there is no possible prioritized attribute list, return "IMPOSSIBLE" instead, and if there is more than one possible answer, return "TOO MANY" (all quotes for clarity).
 

Definition

    
Class:LostSortingAlgorithm
Method:recoverSortingAlgorithm
Parameters:String[]
Returns:String
Method signature:String recoverSortingAlgorithm(String[] clues)
(be sure your method is public)
    
 

Constraints

-clues will contain between 1 and 50 elements, inclusive.
-Each element of clues will contain between 1 and 8 characters, inclusive.
-Each element of clues will contain only digits ('0'-'9') and uppercase letters ('A'-'F').
-All elements of clues will be of the same length.
-All elements of clues will be distinct.
 

Examples

0)
    
{"12D", "23A", "33A", "13B"}
Returns: "120"
The example from the statement. Four elements of the input represent four houses, where the first character of each element represents the cost ('1' corresponds to $100,000, '2' - to $200,000, and 3 - to $300,000), the second character represents the number of bedrooms, and the third character of each element represents the distance to work ('A' corresponds to 10 minutes, 'B' - to 20 minutes and 'D' - to 30 minutes). The prioritized list of attributes in this case must be "120" (number of bedrooms, distance from work, cost - this is the example we used above).
1)
    
{"0112", "2102", "1010"}
Returns: "IMPOSSIBLE"
2)
    
{"F112", "21F2", "1F1F"}
Returns: "TOO MANY"
3)
    
{"01234567", "01234568"}
Returns: "TOO MANY"
4)
    
{"0","1","2","3","4","7","6"}
Returns: "IMPOSSIBLE"
5)
    
{"0123","1234","2345","0145","1245","2346"}
Returns: "IMPOSSIBLE"
6)
    
{"0123","0145","1234","1245","2345","2346"}
Returns: "TOO MANY"
7)
    
{"CC0","2F0","4A1","FB1","542","362","462","172"}
Returns: "210"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Steganography

Encryption/Compression



Used in:

MM 41

Used as:

Division I Level One

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10056

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13566&pm=10056

Problem Statement

    

Steganography is the process of transmitting a message by hiding it in such a way that it is not apparent there is a secret message. By comparison, typical encryption methods obscure a message in such a way that it can not be interpreted by others, but it is clear that a message is being transmitted. With a steganographic process, an uninitiated observer would have no cause for suspicion.

One of the most common forms of steganography is to send bitmapped images, where the lowest order bits of some of the pixels actually contain a secret message of some kind. Since only the lower few bits of any given pixel are altered from the original image, the image containing a secret message looks virtually identical to the casual observer.

You will be given an image. The image is given in int[] pixels. You are also given ints width and height. A pixel (x, y) of the image is given in element y * width + x of pixels. Each value is the RGB encoding of the three channels, pixel = red * 65536 + green * 256 + blue. Encoded within that image will be a second image, which is the secret message you are attempting to discover.

To generate test cases, two images from a set of 500 will be chosen at random. One will be the carrier image, and will be used at it's original size. The second will have a portion used as the hidden image. A size for the hidden image is chosen, with a minimum size of 50x50 and a maximum size of 200x200 (not necessarily square). Then, a section of the chosen size is extracted from the second image, to be used as the hidden image. Then, hiddenWidth distinct columns of the carrier image are chosen at random as xx[], as are hiddenHeight distinct rows, as yy[]. xx[] and yy[] are then sorted. Finally, the number of bits to use for the hidden image, k, is chosen between 2 and 4. The hidden image is then reduced to only use that many bits for each R, G, B channel. This is done by taking each R/G/B value for each pixel, and bit shifting it to the right by 8-k. Finally, the RGB values of each pixel (x, y) of the hidden image replace the k lowest order bits of each RGB channel of pixel(xx[x], yy[y]) in the carrier image.

Your solution should return a String[], where each element is a space-delimited list of integers, and each integer represents a pixel. Since you are returning the representation of a rectangular image, each element of the return should contain the same number of integers. Each integer should be encoded in the RGB format as described previously in the problem.

Your score is calculated by determining how many pixels of your returned image exactly match the pixels of the actual hidden image. Since the return may have more or less rows or columns than the actual image, your returned image will be compared against the actual image, adjusted by each possible offset in the x and y directions, taking the best value. Then, letting best = #pixels matched, your score is calculated as best^2 / yourArea / actualArea. Your final score will be the sum of your score from each individual test case.

 

Definition

    
Class:Steganography
Method:findImage
Parameters:int[], int, int
Returns:String[]
Method signature:String[] findImage(int[] pixels, int width, int height)
(be sure your method is public)
    
 

Notes

-Test cases are chosen using http://commons.wikimedia.org/wiki/Special:Random/Image . Images which are not primarily photographic or photo-realistic, such as line drawings, are discarded.
-Neither image dimension will be more than 500 pixels - larger images will be scaled so that the larger dimension becomes 500.
 

Constraints

-The time limit is 10 seconds, and the memory limit is 1GB.
-There are 50 non-example test cases.
 

Examples

0)
    
"1"
Returns: ""
Carrier Image: http://www.topcoder.com/contest/problem/Steganography/original0.png Hidden Image: http://www.topcoder.com/contest/problem/Steganography/hidden0.png With Hidden Image: http://www.topcoder.com/contest/problem/Steganography/steg0.png Bits Used: 2
1)
    
"2"
Returns: ""
Carrier Image: http://www.topcoder.com/contest/problem/Steganography/original1.png Hidden Image: http://www.topcoder.com/contest/problem/Steganography/hidden1.png With Hidden Image: http://www.topcoder.com/contest/problem/Steganography/steg1.png Bits Used: 2
2)
    
"3"
Returns: ""
Carrier Image: http://www.topcoder.com/contest/problem/Steganography/original2.png Hidden Image: http://www.topcoder.com/contest/problem/Steganography/hidden2.png With Hidden Image: http://www.topcoder.com/contest/problem/Steganography/steg2.png Bits Used: 4
3)
    
"4"
Returns: ""
Carrier Image: http://www.topcoder.com/contest/problem/Steganography/original3.png Hidden Image: http://www.topcoder.com/contest/problem/Steganography/hidden3.png With Hidden Image: http://www.topcoder.com/contest/problem/Steganography/steg3.png Bits Used: 3
4)
    
"5"
Returns: ""
Carrier Image: http://www.topcoder.com/contest/problem/Steganography/original4.png Hidden Image: http://www.topcoder.com/contest/problem/Steganography/hidden4.png With Hidden Image: http://www.topcoder.com/contest/problem/Steganography/steg4.png Bits Used: 2
5)
    
"6"
Returns: ""
6)
    
"7"
Returns: ""
7)
    
"8"
Returns: ""
8)
    
"9"
Returns: ""
9)
    
"10"
Returns: ""

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CactusAutomorphisms

Graph Theory, Math



Used in:

SRM 419

Used as:

Division I Level Three

Writer:

andrewzta

Testers:

PabloGilberto , Olexiy , marek.cygan , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10055

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13510&pm=10055

Problem Statement

    

A vertex cactus is a connected graph such that each vertex belongs to at most one simple cycle. A simple cycle is a cycle that doesn't pass through any vertex more than once. For example, the graph in the picture below is a vertex cactus:

Given a graph G with vertices numbered from 1 to n, its automorphism is a permutation p[1], p[2], ..., p[n] such that there is an edge i-j in G if and only if there is an edge p[i]-p[j].

You are given an int n - the number of vertices in a vertex cactus. The vertices are numbered 1 to n. The edges of the graph are given to you in the String[] edges. Concatenate the elements of edges to get a comma-separated list of integer pairs. The integers in each pair are separated by a space. The pair "i j" (quotes for clarity) means that there is an edge between vertices i and j in the given graph. Return the number of automorphisms that exist for the given vertex cactus, modulo 10^9+3.

 

Definition

    
Class:CactusAutomorphisms
Method:count
Parameters:int, String[]
Returns:int
Method signature:int count(int n, String[] edges)
(be sure your method is public)
    
 

Constraints

-n will be between 1 and 200, inclusive.
-edges will contain between 0 and 50 elements, inclusive.
-Each element of edges will contain between 1 and 50 characters, inclusive.
-When concatenated edges will contain a comma separated list of pairs of integers.
-Each integer pair will contain two distinct integers between 1 and n, inclusive, separated by a space.
-The given graph will be a vertex cactus - it will be connected and each vertex will belong to at most one simple cycle.
-Every pair of vertices in the graph will be connected by at most one edge.
 

Examples

0)
    
4
{"1 2,1 3,1 4"}
Returns: 6
We can arbitrarily permute vertices 2, 3 and 4.
1)
    
4
{"1 2,2 3,3 4,4 1"}
Returns: 8
The permutation can either perform a circular shift of the vertices along the cycle, or flip the cycle, or both.
2)
    
6
{"1 2,2 3,3 1,4 5,5 6,6 4,1 4"}
Returns: 8
The permutation can swap triangles. Also, in each triangle, the permutation can swap the two vertices that are not incident to another triangle.
3)
    
18
{"1 2,2 3,3 4,2 4,1 5,1 10,5 10,5 6,6 7",
 ",7 8,7 16,7 17,7 9,6 9,10 18,18 ",
 "12,12 11,11 18,12 13,12 14,12 15"}
Returns: 144
This is the graph in the picture in the problem statement.
4)
    
1
{}
Returns: 1
5)
    
200
{"1 2,2 3,3 4,4 5,5 6,6 7,7 8,8 9,9 10,10 11,11 2,1 ",
 "12,12 13,13 14,14 15,15 16,16 17,17 18,18 19,19 20",
 ",20 21,21 12,1 22,22 23,23 24,24 25,25 26,26 27,27",
 " 28,28 29,29 30,30 31,31 22,1 32,32 33,32 34,34 35",
 ",35 36,36 32,1 37,37 38,37 39,39 40,40 41,41 37,1 ",
 "42,42 43,42 44,44 45,45 46,46 42,1 47,47 48,47 49,",
 "49 50,50 51,51 47,1 52,52 53,52 54,54 55,55 56,56 ",
 "52,1 57,57 58,57 59,59 60,60 61,61 57,1 62,62 63,6",
 "2 64,64 65,65 66,66 62,1 67,67 68,67 69,69 70,70 7",
 "1,71 67,1 72,72 73,72 74,74 75,75 76,76 72,1 77,77",
 " 78,78 79,79 80,80 81,81 77,1 82,82 83,83 84,84 85",
 ",85 86,86 82,1 87,87 88,88 89,89 90,90 91,91 87,1 ",
 "92,92 93,93 94,94 95,95 96,96 92,1 97,97 98,98 99,",
 "99 100,100 101,101 97,1 102,102 103,103 104,104 10",
 "5,105 106,106 102,1 107,107 108,108 109,109 110,11",
 "0 111,111 107,1 112,112 113,113 114,114 115,115 11",
 "6,116 112,1 117,117 118,118 119,119 120,120 121,12",
 "1 117,1 122,122 123,123 124,124 125,125 126,126 12",
 "2,1 127,127 128,128 129,129 130,130 131,131 127,1 ",
 "132,132 133,133 134,134 135,135 136,136 132,1 137,",
 "137 138,138 139,139 140,140 141,141 137,1 142,142 ",
 "143,142 144,142 145,1 146,146 147,146 148,146 149,",
 "1 150,150 151,150 152,150 153,1 154,154 155,154 15",
 "6,154 157,1 158,158 159,158 160,158 161,1 162,162 ",
 "163,162 164,162 165,1 166,166 167,167 168,166 169,",
 "166 170,166 171,166 172,1 173,173 174,174 175,173 ",
 "176,173 177,173 178,173 179,1 180,180 181,181 182,",
 "180 183,180 184,180 185,180 186,1 187,187 188,188 ",
 "189,187 190,187 191,187 192,187 193,1 194,194 195,",
 "195 196,194 197,194 198,194 199,194 200"}
Returns: 886565533

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MegaParty

Geometry, Graph Theory



Used in:

Marathon Match 49

Used as:

Division I Level One

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10032

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13709&pm=10032

Problem Statement

    

Introduction

You want to run a party and to invite all your friends to come. The problem is, not all of your friends like each other. You want to place everybody in as little room as possible so that everybody feels as comfortable as possible.

Details

The relationships between your friends are described with a NxN matrix a: aij=1 denotes that i and j are friends, aij=-1 denotes that i and j are enemies, and aij=0 means that i and j feel neutral about each other. Moreover, the feelings of some of your friends are more important to you than the feelings of other, bi denoting the importance of person i to you.

Placing N people in the room is modeled as arranging N points on the plane. To calculate the quality of the arrangement, the following rules are used:
  • no two points can be placed closer than 10, so if the distance between points i and j is strictly less than 10, the quality of the arrangement is equal to 0.
  • the happiness of person i hi is the number of his friends who are placed at distance not greater than e1 from him minus the number of his enemies who are placed at distance not greater than e2 from him.
  • the area of the arrangement is (max (xi) - min (xi) + 20) * (max (yi) - min (yi) + 20).
  • finally, the quality of the arrangement is the sum of hi*bi over all points divided by the area of the arrangement.

Implementation

You will be given int[]s A and B (aij=A[i*N+j], bi=B[i]) and doubles e1 and e2 (you can deduce N as the number of elements in B). Your return will describe the arrangement of the points on the plane and must contain exactly 2*N elements, elements 2*i and 2*i+1 being x and y-coordinates of point i on the plane.

Scoring

Your score for an individual test case will be the quality of the arrangement described with your return. Negative scores will be replaced with 0. Your overall score will the sum of YOU/BEST, where YOU = your score and BEST = the best score for anyone on that test case.

Test Generation

To generate a, first the numbers p(1) and p(-1) are chosen between 0.1 and 0.5. Each element of a above the diagonal (a[i][j] with j>i) is generated randomly and independently so that it is 1 with probability p(1), -1 with probability p(-1) and 0 with probability (1-p(1)-p(-1)). The elements below the diagonal are then set to mirror those above (aij=aji). After this a is modified for 2*N*N iterations in the following way: on each iteration, a random triple of distinct indices i1, i2 and i3 is chosen, and if the set of elements a[i1][i2], a[i1][i3] and a[i2][i3] contains one -1 and two 1 or three -1, the triple is considered to be unstable and element a[i1][i2] is inverted.



Visualization

A visualization tool is available for offline testing at http://www.topcoder.com/contest/problem/MegaParty/manual.html.
 

Definition

    
Class:MegaParty
Method:arrangement
Parameters:int[], int[], double, double
Returns:double[]
Method signature:double[] arrangement(int[] A, int[] B, double e1, double e2)
(be sure your method is public)
    
 

Notes

-All parameters (except for A) are chosen randomly and uniformly (except for N in first three tests).
-Euclidean distance is used to calculate the distance between two points.
-Invalid return of any kind will result in zero absolute score for that test case.
-The memory limit is 1024 MB and the time limit is 20 seconds (which includes only time spent in your code).
-There are 10 example test cases and 100 full submission test cases.
 

Constraints

-N will be between 10 and 1000, inclusive.
-e1 and e2 will be between 10 and 100, inclusive.
-Each element of A will be 1, -1 or 0, A[i*N+i]=0, A[i*N+j]=A[j*N+i].
-Each element of B will be between 0 and 10, inclusive.
 

Examples

0)
    
"1"
Returns: "seed = 1
N = 10
e1 = 79.90537473458491
e2 = 87.73517325544584
"
1)
    
"2"
Returns: "seed = 2
N = 50
e1 = 69.0075415716353
e2 = 13.65589320322015
"
2)
    
"3"
Returns: "seed = 3
N = 100
e1 = 36.08279169755407
e2 = 83.35353433161342
"
3)
    
"4"
Returns: "seed = 4
N = 761
e1 = 49.3674457914687
e2 = 77.57082451444492
"
4)
    
"5"
Returns: "seed = 5
N = 852
e1 = 11.621835296956831
e2 = 97.48383017983551
"
5)
    
"6"
Returns: "seed = 6
N = 586
e1 = 27.53708937356408
e2 = 15.397192389252275
"
6)
    
"7"
Returns: "seed = 7
N = 506
e1 = 88.36666714437418
e2 = 53.13863217801227
"
7)
    
"8"
Returns: "seed = 8
N = 289
e1 = 64.46620025547209
e2 = 80.53024200739404
"
8)
    
"9"
Returns: "seed = 9
N = 164
e1 = 22.80606053590618
e2 = 78.18281248212246
"
9)
    
"10"
Returns: "seed = 10
N = 620
e1 = 14.821168809032962
e2 = 84.22929341728343
"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FeudaliasWar

Graph Theory, Search



Used in:

SRM 438

Used as:

Division I Level Three

Writer:

vexorian

Testers:

PabloGilberto , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10027

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13803&pm=10027

Problem Statement

    Feudalia's military is preparing a preemptive strike against Banania's military installations. Feudalia has a number of missile silos. Each silo has an unlimited number of missiles at its disposal, but can only fire a single missile at a time. When a missile is fired, it requires takeOffTime seconds before it can take off from its silo. Once it takes off, it requires distance/missileSpeed minutes to reach its target, where distance is the Euclidean distance between the silo and the target. When the missile reaches its target, the target is instantly destroyed. After a missile takes off, its silo requires rechargeTime minutes of preparation before it can launch another missile.



The general has ordered you to destroy all of Banania's military bases in as little time as possible. You are given int[]s siloX, siloY, baseX and baseY which determine the locations of the missile silos and bases. Feudalia's i-th missile silo is located at (siloX[i], siloY[i]) and Banania's j-th base is located at (baseX[j], baseY[j]). Return the minimum time in minutes required to destroy all enemy bases.
 

Definition

    
Class:FeudaliasWar
Method:getMinimumTime
Parameters:int[], int[], int[], int[], int, int, int
Returns:double
Method signature:double getMinimumTime(int[] baseX, int[] baseY, int[] siloX, int[] siloY, int takeOffTime, int rechargeTime, int missileSpeed)
(be sure your method is public)
    
 

Notes

-The returned value must be accurate to within a relative or absolute value of 1E-9.
 

Constraints

-takeOffTime will be between 1 and 60, inclusive.
-rechargeTime will be between 5 and 1000, inclusive.
-missileSpeed will be between 1 and 2000, inclusive.
-baseX will contain between 1 and 50 elements, inclusive.
-baseY will contain the same number of elements as baseX.
-siloX will contain between 1 and 50 elements, inclusive.
-siloY will contain the same number of elements as siloX.
-Each element of baseX, baseY, siloX and siloY will be between 0 and 1000000, inclusive.
-The locations for each base and silo will be distinct.
 

Examples

0)
    
{0,0,50}
{0,50,0}
{50,0,1000}
{50,1000,0}
30
20
1
Returns: 91.5
An optimal strategy would be:

00:00 : The silo at (50,50) launches an attack against the base at (0,0).

00:30 : The first missile finishes taking off.

20:30 : The silo at (50,50) launches its second missile, this time against the base at (0,50).

21:00 : The second missile finishes taking off.

41:30 : The silo at (50,50) launches its third missile, this time against the base at (50,0).

71:00 : The second missile hits the base at (0,50) (The distance was 50).

71:12.6 (Approx.) : The first missile hits the base at (0,0) (The distance was 70.710678119).

91:30 : The third missile hits the remaining base.
1)
    
{0,0,50}
{0,50,0}
{50,0,1000}
{50,1000,0}
30
900
1
Returns: 950.5
Since it now takes 15 hours to prepare a new missile, using the same silo against the three enemy bases is no longer the optimal strategy. Instead, each of the silos at (0,1000) and (1000,0) should target the closest base while the silo at (50,50) targets the base at (0,0).
2)
    
{0,2000,4000,6000,8000}
{0,2000,4000,6000,8000}
{0,2000,4000,6000}
{2000,4000,6000,8000}
60
1000
50
Returns: 1042.0
3)
    
{1100,1200,1300,1400,1500,1600,1700,1800,1900}
{2100,2300,2500,2700,2900,2700,2500,2300,2100}
{1400,1400,1500,1600,1600}
{3100,3300,3200,3100,3300}
20
300
100
Returns: 306.7494291969649

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BarbarianInvasion

Graph Theory



Used in:

SRM 433

Used as:

Division I Level Three

Writer:

gojira_tc

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10013

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13695&pm=10013

Problem Statement

    A kingdom is being threatened by a barbarian invasion from all sides. It was decided that the aggressors must not reach the capital. You are given a String[] countryMap containing a map of the kingdom. The kingdom is represented as a rectangular grid of equal squares. The j-th character of the i-th element of countryMap corresponds to the square at row i, column j. The capital square is marked with a '*', impassable squares are marked with '-', and all other squares are marked with uppercase letters representing different types of open terrain.



You must deploy detachments to open squares in such a way that the capital square is unreachable from the border. In other words, to ensure that no aggressors can reach the capital, each path from the border to the capital must be blocked by an impassable square or a detachment. The enemy can only move directly north, east, south and west between open squares that share common sides. Therefore, only consider paths where each pair of consecutive squares has a common side.



Each type of terrain requires a detachment of a certain size. You are given a int[] detachmentSize, where element 0 is the size of a detachment required for each square of terrain type 'A', element 1 is the required size for terrain type 'B', and so on. Each detachment contains a commander, and qualified commanders are hard to come by. Therefore, your primary goal is to minimize the total number of detachments required. If there are multiple ways to defend the capital using the minimum possible number of detachments, choose the one among them that minimizes the total size of all the detachments. Return the total size of all the detachments.
 

Definition

    
Class:BarbarianInvasion
Method:minimalDetachment
Parameters:String[], int[]
Returns:int
Method signature:int minimalDetachment(String[] countryMap, int[] detachmentSize)
(be sure your method is public)
    
 

Constraints

-countryMap will contain between 3 and 50 elements, inclusive.
-Each element of countryMap will contain between 3 and 50 elements, inclusive.
-Elements of countryMap will be of the same length.
-Each element of countryMap will contain only uppercase letters, minus signs and asterisks ('A'-'Z','-','*').
-countryMap will contain exactly one character '*'.
-The '*' character will not be in the first or last row or column of countryMap.
-detachmentSize will contain exactly 26 elements.
-Each element of detachmentSize will be between 1 and 1000000, inclusive.
 

Examples

0)
    
{"ABA",
 "A*A",
 "AAA"}
{1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
Returns: 5
We have no other way than blocking the squares adjacent to the capital, so the minimal total size of the detachments is 5.
1)
    
{"CCCC",
 "-BAC",
 "-*AC",
 "--AC"}
{5,20,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
Returns: 25
Having enough commanders, it could be possible to block the way with 7 detachments standing on the border with the total size of 7. But our primary goal is to minimize the number of detachments, so we have to block 'B' and 'A' squares adjacent to the capital.
2)
    
{"A----A",
 "-AAAA-",
 "-AA*A-",
 "-AAAA-",
 "A----A"}
{9,8,2,5,3,2,1,2,6,10,4,6,7,1,7,8,8,8,2,9,7,6,5,1,5,10}
Returns: 0
There is already no way to reach the capital from the border.
3)
    
{"-A-----",
 "-BCCC*-",
 "-A-----"}
{1,5,10,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
Returns: 5
Blocking 'B' is the optimal decision.
4)
    
{"WANNABRUTEFORCEMEHUH",
 "ASUDQWNHIOCASFIUQISA",
 "UWQD-ASFFC-AJSQOOWE-",
 "-----*Y--AVSSFIUQISA",
 "UWQD-ASFFC-AJSQOOWE-",
 "JUFDIFD-CHBVISBOOWE-",
 "WANNABRUTEFORCEMEHUH"}
{87,78,20,43,30,12,9,18,57,93,32,60,64,9,69,74,74,78,12,81,63,57,48,8,44,95}
Returns: 218

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MazeWandering

Graph Theory, Math, Recursion



Used in:

SRM 440

Used as:

Division I Level Two

Writer:

gojira_tc

Testers:

PabloGilberto , ivan_metelsky , Vasyl[alphacom]

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10005

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13748&pm=10005

Problem Statement

    According to research conducted recently, listening to classical music increases one's mental abilities, while listening to metal decreases them. Now, yet another experiment is being conducted to try to prove or disprove this statement.



In this new experiment, a mouse is placed in a rectangular maze consisting of NxM squares. Each square either contains a wall or is empty. The maze is structured in such a way that for any two empty squares, there exists exactly one path between them. A path is a sequence of pairwise distinct empty squares such that every two consecutive squares are neighboring. Two squares are considered neighboring if they share a common edge.



One of the empty squares in the maze contains a piece of cheese, and the mouse's goal is to reach that square. The mouse can only move between neighboring empty squares. The mouse has been listening to metal for a week, so his mental abilities have become absolutely dull. Not only can he not smell the cheese, he can't even remember where he was heading a moment ago, so he is just wandering randomly. More precisely, from each square, the mouse will randomly choose one of the neighboring empty squares and move there. The probability of choosing each of the squares is equal. Each move takes one second.



You are given a String[] maze representing the maze. It contains N elements, each containing M characters. Empty squares are denoted by '.', walls are denoted by uppercase 'X', and the square containing the cheese is denoted by '*'. For each empty square, calculate the expected time required for the mouse to reach the cheese starting from that square. Return the arithmetical mean of all the expected times.
 

Definition

    
Class:MazeWandering
Method:expectedTime
Parameters:String[]
Returns:double
Method signature:double expectedTime(String[] maze)
(be sure your method is public)
    
 

Notes

-The returned value must have an absolute or relative error less than 1e-9.
 

Constraints

-maze will contain between 1 and 50 elements, inclusive.
-Each element of maze will contain between 1 and 50 characters, inclusive.
-Elements of maze will be of the same length.
-maze will contain only '.', 'X', or '*' characters.
-There will be exactly one '*' character in maze.
-For every pair of empty squares in the maze, there will exist exactly one path between them.
 

Examples

0)
    
{"*",
 "."}
Returns: 0.5
The mouse will need 0 seconds to find the cheese if it is put in the cheese-square and 1 second otherwise.
1)
    
{"*.."}
Returns: 2.3333333333333335
The expectations for each square are 0.0, 3.0 and 4.0.
2)
    
{"...",
 "X*X",
 "..."}
Returns: 4.857142857142857
3)
    
{".*.",
 ".XX",
 "..."}
Returns: 13.714285714285714
4)
    
{"*........",
 "XXX.XXXX.",
 ".XX.X....",
 ".....XX.X"}
Returns: 167.2608695652174

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Playlist

Simple Search, Iteration, Simulation



Used in:

TCHS SRM 56

Used as:

Division I Level Two

Writer:

DStepanenko

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9985

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13525&pm=9985

Problem Statement

    

You have n distinct songs in your music player, numbered 1 through n. Some of these songs are good and the rest are bad. The good songs are given in the int[] best.

Your task is to order your songs into a playlist where each song appears exactly once. The goal is to maximize the total number of times you hear a good song in shuffle mode. In shuffle mode, your music player plays the a[0]-th song in your playlist, followed by the a[1]-th song, etc. All indices are 1-based. If the same song is played multiple times, each time counts toward the total.

Return a int[] containing the playlist that will achieve this goal. If there are multiple possible return values, choose the one that comes earliest lexicographically. A int[] a comes before a int[] b if a contains a smaller element at the first index where they differ.

 

Definition

    
Class:Playlist
Method:trackSort
Parameters:int, int[], int[]
Returns:int[]
Method signature:int[] trackSort(int n, int[] best, int[] a)
(be sure your method is public)
    
 

Constraints

-n will be between 1 and 50, inclusive.
-best will contain between 0 and n elements, inclusive.
-All elements of best will be distinct.
-a will contain between 0 and 50 elements, inclusive.
-Each element of best and a will be between 1 and n, inclusive.
 

Examples

0)
    
3
{1, 2}
{3, 2, 3, 3, 1, 2}
Returns: {3, 1, 2 }
There are 3 songs, and songs 1 and 2 are good. If you order the tracks in your playlist {3, 1, 2} or {3, 2, 1}, you will hear a good song 5 times in shuffle mode. In case of a tie, you should choose the one that comes earliest lexicographically, so the answer is {3, 1, 2}.
1)
    
5
{}
{1, 2, 3, 5, 4}
Returns: {1, 2, 3, 4, 5 }
In this case, there are no good songs, so you should just choose the playlist that comes first lexicographically: {1, 2, 3, 4, 5}.
2)
    
6
{3, 5}
{1, 2, 3, 4, 5, 2, 3, 2, 6}
Returns: {1, 3, 5, 2, 4, 6 }
3)
    
3
{3, 2, 1}
{3, 1, 2, 3, 2, 1, 2, 1, 3}
Returns: {1, 2, 3 }
4)
    
5
{4, 5, 3}
{5, 5, 5, 3, 2, 1, 4, 3}
Returns: {1, 2, 3, 4, 5 }
5)
    
10
{8, 5, 1, 7}
{6, 6, 4, 4}
Returns: {1, 2, 3, 5, 4, 7, 6, 8, 9, 10 }
6)
    
8
{6}
{2, 8, 3, 1, 5, 7, 7, 8, 4, 4}
Returns: {1, 2, 3, 4, 5, 7, 6, 8 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ChangeOMatic

Dynamic Programming, Greedy, Simple Math



Used in:

SRM 420

Used as:

Division I Level Three

Writer:

misof

Testers:

PabloGilberto , Olexiy , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9963

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13511&pm=9963

Problem Statement

    

The Change-O-Matic is a deterministic machine with a single goal: to provide change. That is, you throw in a banknote or a coin, and the machine throws out a bunch of smaller coins with the same total value.

More precisely, the Change-O-Matic operates as follows:

The machine contains several large stacks of coins. The values of these coins are given as a int[] outputValues. For the purpose of this problem we may assume that the machine contains an infinite number of coins of each of these values. One of the available values is always 1.

The customer may throw in any coin or banknote with value greater than 1. The machine will output a set of at least two coins with the same total value. If there are multiple ways to satisfy this requirement, the machine prefers the one where the total number of output coins is minimized. If there are still multiple ways, the machine prefers the one that is lexicographically maximal (see Notes for a precise definition).

You have a single banknote, and its value is given as a long inputValue. You would like to change it into coins of value 1 each. Return the number of times you have to throw something into the machine.

 

Definition

    
Class:ChangeOMatic
Method:howManyRounds
Parameters:int[], long
Returns:long
Method signature:long howManyRounds(int[] outputValues, long inputValue)
(be sure your method is public)
    
 

Notes

-Let A=(a1,...,aN) and B=(b1,...,bN) be two different but equally large sets of coins, with a1 >= a2 >= ... >= aN and b1 >= b2 >= ... >= bN. Let x be the smallest index such that ax != bx. If ax > bx, we say that the set A is lexicographically larger than the set B.
-Given a collection of different but equally large sets of coins, the lexicographically maximal set is the one that is lexicographically larger than each of the other sets. (Note that there is always exactly one such set.)
 

Constraints

-outputValues will contain between 1 and 50 elements, inclusive.
-outputValues will be sorted in strictly ascending order. That is, for each i, outputValues[i] < outputValues[i+1].
-Each element of outputValues will be between 1 and 1,000, inclusive.
-Element 0 of outputValues will be equal to 1.
-inputValue will be between 2 and 10^15, inclusive.
 

Examples

0)
    
{1,5,10}
21
Returns: 7
The process of changing your money may look as follows:
You insert:    You get:      You then have:
21             10+10+1       10+10+1
10             5+5           10+5+5+1
5              1+1+1+1+1     10+5+1+1+1+1+1+1
10             5+5           5+5+5+1+1+1+1+1+1
5              1+1+1+1+1     5+5+(eleven times 1)
5              1+1+1+1+1     5+(sixteen times 1)
5              1+1+1+1+1     twenty-one coins worth 1 each
1)
    
{1,33,90,91,92,93,94,95,96,97,98}
99
Returns: 12
In each step, the machine minimizes the number of coins it throws out, not the number of steps you need to accomplish your task. In the first step it will output a coin worth 98 and a coin worth 1.
2)
    
{1,30,60}
50
Returns: 2
The value of the banknote may be less than the values of some coin types.
3)
    
{1,30,60,90}
60
Returns: 3
The value of the banknote may even be equal to the value of some coin type. Note that for any input the machine must always output at least two coins. Therefore if you throw in the banknote worth 60, you will get two coins worth 30 each.
4)
    
{1,8,9,11,12,100}
120
Returns: 37
In the first step the machine would output 100+12+8. (The combination 100+11+9 has the same number of coins, but 100+12+8 is lexicographically larger.)

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TemplateMatching

Brute Force, String Parsing



Used in:

SRM 417

Used as:

Division I Level One , Division II Level Two

Writer:

Pawa

Testers:

PabloGilberto , Olexiy , ivan_metelsky , Xixas

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9943

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13508&pm=9943

Problem Statement

    

In this problem you will be given a String text and you will need to find the substring of the text that matches a given template in the best way. The template will be represented by two Strings: prefix and suffix. Consider a string S. The prefix match score of S with respect to a given template is the maximal n >= 0 such that the first n characters of S are equal to the last n characters of prefix and occur in the same exact order. Analogously, the suffix match score of S is the maximal m >= 0 such that the last m characters of S are equal to the first m characters of suffix and occur in the same exact order.



For example, if S = "something", prefix = "awesome", and suffix = "ingenious", than the prefix score of S is 4 (the matched characters are "some") and the suffix score is 3 (the matched characters are "ing").



The match score of a string S with respect to a given template is the sum of its prefix and suffix match scores. Find the non-empty substring of text with the maximal match score according to the template (prefix, suffix). In case of a tie, return the substring with the maximal prefix score. If there are still several candidates, return one that comes first lexicographically.

 

Definition

    
Class:TemplateMatching
Method:bestMatch
Parameters:String, String, String
Returns:String
Method signature:String bestMatch(String text, String prefix, String suffix)
(be sure your method is public)
    
 

Notes

-String A comes before string B lexicographically if A is a proper prefix of B, or if A has a smaller character at the first position where the strings differ. When comparing the characters, refer to the following list of characters in ascending order: ' ', 'a', 'b', ..., 'z'.
 

Constraints

-text will contain between 1 and 50 characters, inclusive.
-prefix will contain between 1 and 50 characters, inclusive.
-suffix will contain between 1 and 50 characters, inclusive.
-text, prefix and suffix will contain only lowercase letters ('a'-'z') and spaces (' ').
 

Examples

0)
    
"something"
"awesome"
"ingenious"
Returns: "something"
The example from the problem statement.
1)
    
"havka"
"eto"
"papstvo"
Returns: "a"
The return value must be non-empty string, so the correct answer is "a".
2)
    
"abracadabra"
"habrahabr"
"bracket"
Returns: "abrac"
3)
    
"mississippi"
"promise"
"piccolo"
Returns: "ippi"
4)
    
"a a a a a a"
"a a"
"a"
Returns: "a a"
5)
    
"ab"
"b"
"a"
Returns: "b"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WalkingDistance

Geometry, Graph Theory, Math



Used in:

SRM 417

Used as:

Division I Level Three

Writer:

Pawa

Testers:

PabloGilberto , Olexiy , ivan_metelsky , Xixas

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9924

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13508&pm=9924

Problem Statement

    

A map of the city consists of a number of streets connecting several junctions. All the streets are straight line segments connecting two junctions, organized in such a way that starting at any junction and walking along the streets one can reach any other junction. The walking distance between two points (each either a junction or some intermediate point of a street) in the city is the shortest path from the first point to the second, if you are allowed to walk only along the streets. The length of the street is the Cartesian distance between its ends. Streets never intersect outside the junctions. Tunnels and overpasses are used whenever necessary to achieve this (see example 1 for further clarification).



Given a map of the city, your goal is to find the maximal walking distance among any two points in the city. The map of the city is provided as follows. You are given two int[]s x and y, each of the same length N. These two int[]s represent N junctions with Cartesian coordinates (x[i], y[i]) for i = 0..N-1. You are also given a String[] streets, where the j-th element of streets[i] is 'Y' if the junctions i and j are connected by a street, and 'N' otherwise.

 

Definition

    
Class:WalkingDistance
Method:getLongestShortest
Parameters:int[], int[], String[]
Returns:double
Method signature:double getLongestShortest(int[] x, int[] y, String[] streets)
(be sure your method is public)
    
 

Notes

-Your return value must have an absolute or relative error less than 1e-9.
 

Constraints

-x and y and streets will each contain between 2 and 50 elements, inclusive.
-x, y and streets will have the same number of elements.
-Each element of x and y will be between -1000 and 1000, inclusive.
-Each element of streets will contain exactly n characters, where n is the number of elements in streets.
-Each element of streets will contain only 'N' and 'Y' characters.
-The i-th character of the i-th element of streets will always be 'N'.
-The i-th character of the j-th element of streets will always be equal to the j-th character of the i-th element of streets.
-All junctions represented by x and y will be distinct.
-There will be a path between every pair of junctions.
 

Examples

0)
    
{0,1}
{0,1}
{"NY","YN"}
Returns: 1.4142135623730951
There are just two junctions conntected by a road. So the answer is the length of the street, which is the square root of 2.
1)
    
{0,2,2,0}
{0,0,2,2}
{"NNYY","NNYY","YYNN","YYNN"}
Returns: 4.82842712474619
Both points on which this maximal shortest distance is achieved have coordinates (1, 1), but they are located on different streets.
2)
    
{0,1,0}
{0,0,1}
{"NYY","YNY", "YYN"}
Returns: 1.7071067811865475
The three junctions form a right isosceles triangle. Two points for which the maximal walking distance is achieved are (0,0) and (1/2, 1/2).
3)
    
{0, 1, 2}
{0, 1, 2}
{"NYY", "YNN", "YNN"}
Returns: 4.242640687119286

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DancingCouples

Dynamic Programming, Graph Theory



Used in:

SRM 416

Used as:

Division II Level Three

Writer:

xOberon

Testers:

PabloGilberto , Olexiy , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9902

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13507&pm=9902

Problem Statement

    

There are N boys and M girls in a dance school. The teachers are organizing a performance and they need exactly K boy-girl couples for their show. Unfortunately, this is not a straightforward task since some children cannot be paired with each other (due to differences in height, skill, etc.). One of the teachers is a computer science graduate, and has decided to count the number of ways to select K couples.

You are given a String[] canDance containing exactly N elements, each with exactly M characters. The j-th character of the i-th element of canDance is 'Y' if boy i can be paired with girl j, and 'N' otherwise. Return the number of distinct valid ways to select exactly K boy-girl pairs.

 

Definition

    
Class:DancingCouples
Method:countPairs
Parameters:String[], int
Returns:int
Method signature:int countPairs(String[] canDance, int K)
(be sure your method is public)
    
 

Constraints

-canDance will contain between 1 and 10 elements, inclusive.
-Each element of canDance will contain between 1 and 10 characters, inclusive.
-Each element of canDance will contain the same number of characters.
-Each character in canDance will be either 'Y' or 'N'.
-K will be between 1 and 10, inclusive.
 

Examples

0)
    
{"YYYY", 
 "YYYY",
 "YYYY"}
3
Returns: 24
There are three boys and four girls. Every boy can dance with every girl. The first boy selects one of the four girls, the second boy selects one of the three remaining girls, and the third boy selects one of the two remaining girls. Thus, there are 4*3*2=24 ways to create three couples.
1)
    
{"YYNN", 
 "NYYN", 
 "NNYY"}
3
Returns: 4
There are 4 possible pairings:

{boy1-girl1, boy2-girl2, boy3-girl3},

{boy1-girl1, boy2-girl2, boy3-girl4},

{boy1-girl1, boy2-girl3, boy3-girl4},

{boy1-girl2, boy2-girl3, boy3-girl4}
2)
    
{"YY", 
 "YY", 
 "YY"}
3
Returns: 0
There are 3 boys but only 2 girls, so it is impossible to select 3 pairs.
3)
    
{"YYNNNN",
 "NYYNNN",
 "NNYYNN",
 "NNNYYN",
 "NNNNYY",
 "YNNNNY"}
3
Returns: 112

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LongStraightRoad

Geometry, Graph Theory



Used in:

SRM 426

Used as:

Division I Level Three

Writer:

StevieT

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9894

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13517&pm=9894

Problem Statement

    

You are driving on a long, straight road, on your way to a place whose name is given in destination. After a while, you lose track of how far you've driven and realize that you may even have driven past your destination without noticing. "Don't worry!" says your friend, who is in the car with you, "I have an excellent memory and can remember not only what was written on every road sign that we have passed, but also what order they were in. Let's continue until we see the next road sign and maybe we'll be able to work out how far we still have to go." You agree to his plan, but don't quite trust his memory as much as he clearly does. You decide that you'll believe what he says as long as it is entirely consistent, otherwise you'll try to find somewhere that you can buy a map.

The information written on each sign is a semi-colon separated list, where each element of the list is the name of a place and the distance to that place from the sign separated by a space. For example, if sign i contained "A 10;B 15" (quotes for clarity) and the sign were located a distance of S[i] units down the road, then the place called "A" would be located P["A"] = S[i] + 10 units down the road and the place called "B" would be located P["B"] = S[i] + 15 units down the road. The distances will never be negative, so only places that are at least as far along the road as the sign can be listed. Note that the values in S[] and P[] need not be integers and that places will have distinct names. You are given the information written on sign i as your friend remembers it in signs[i]. Your friend claims to remember the order of the signs too, so if you wrote down the values of S[i] for each sign, they would be in strictly increasing order (no two signs were colocated).

You are currently at the same position as the sign given in the last element of signs. If the information given in signs is consistent, you can determine the remaining distance to your destination and this distance is non-negative, then return this distance. Otherwise, if there is no way that the data given in signs could represent a set of signs and places as described above, or you cannot determine the distance to your destination from the information in the signs, or you have already driven past your destination, return -1 instead.

 

Definition

    
Class:LongStraightRoad
Method:distanceToDestination
Parameters:String[], String
Returns:int
Method signature:int distanceToDestination(String[] signs, String destination)
(be sure your method is public)
    
 

Notes

-While no two signs were at the same position on the road, places may be legitimately colocated with other places and with the signs.
 

Constraints

-A place is a string containing betweeen 1 and 50 uppercase letters ('A' - 'Z'), inclusive.
-A distance is an integer between 0 and 10000, inclusive, formatted without leading zeros.
-signs will contain between 1 and 50 elements, inclusive.
-Each element of signs will contain between 1 and 50 characters, inclusive.
-Each element of signs will be a semicolon-separated list, each item of which will be a place and a distance, separated by a space.
-No element of signs will contain the same place more than once.
-signs will contain no more than 100 distinct places.
-destination will be a place.
 

Examples

0)
    
{"COLCHESTER 5;GLASTONBURY 25;MARLBOROUGH 13"
,"MARLBOROUGH 2"}
"GLASTONBURY"
Returns: 14
The first sign tells you that GLASTONBURY is 12 units further than MARLBOROUGH. Since you're now 2 units from MARLBOROUGH, you must be 14 units from GLASTONBURY.
1)
    
{"COLCHESTER 5;GLASTONBURY 25;MARLBOROUGH 13"
,"GLASTONBURY 13;MARLBOROUGH 2"}
"GLASTONBURY"
Returns: -1
The distance between GLASTONBURY and MARLBOROUGH has changed between the first and second signs, so they're inconsistent. Even though you are standing next to a sign that tells us how far you are from your destination, return -1.
2)
    
{"A 25;B 15"
,"A 2"}
"B"
Returns: -1
You've driven past your destination by 8 units.
3)
    
{"YVO 60;J 62"
,"K 45"
,"K 40;MV 17"
,"K 37;YVO 44;HY 48;CC 69;D 77;YXF 80"
,"YVO 30;B 37;RB 59"}
"MV"
Returns: 0
You're standing right at your destination.
4)
    
{"A 200;B 150"
,"C 45;D 100;E 150"
,"C 25;E 130"
,"F 80;G 65"
,"G 35;H 160"
,"A 160"
,"H 130"}
"F"
Returns: -1
There is no way the signs could be in this order.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PickingUp

Brute Force, Search



Used in:

SRM 430

Used as:

Division I Level Three

Writer:

Janq

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9887

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13521&pm=9887

Problem Statement

    There are two captains who want to form two teams of equal size. There are N players to choose from, and both captains have given a rating to each of the players. The ratings are given in the long[]s score1 and score2, where score1[i] is the first captain's rating of the i-th player, and score2[i] is the second captain's rating of the i-th player. The total score of a team is defined as the sum of all its players' ratings according to the team's captain. Players must be assigned to the two teams such that the difference between the teams' total scores is as small as possible. Return a int[] containing exactly N elements, where the i-th element is the team to which the i-th player is assigned. The first captain's team is team 1, and the second captain's team is team 2. If multiple solutions exist, return the one that comes first lexicographically.
 

Definition

    
Class:PickingUp
Method:fairPickingUp
Parameters:long[], long[]
Returns:int[]
Method signature:int[] fairPickingUp(long[] score1, long[] score2)
(be sure your method is public)
    
 

Notes

-A sequence A comes before sequence B lexicographically if A has a smaller value at the first position where the sequences differ.
 

Constraints

-score1 and score2 will contain between 2 and 36 elements, inclusive.
-score1 and score2 will contain the same number of elements.
-score1 and score2 will each contain an even number of elements.
-Each element of score1 and score2 will be between 1 and 10^15, inclusive.
 

Examples

0)
    
{5,9}
{8,6}
Returns: {1, 2 }
If we assign the first player to the first team and the second player to the second team, the team scores will be 5 and 6. In the opposite case, the team scores would be 8 and 9. In both cases, the difference is equal to 1. The answer is {1,2} because it comes before {2,1} lexicographically.
1)
    
{2,3,4,7}
{2,4,5,8}
Returns: {1, 2, 2, 1 }
The only way to balance the teams is to assign the first and last players to the first team. The first team's score will be 2+7 and the second team's score will be 4+5.
2)
    
{1,5,6,8}
{7,5,3,1}
Returns: {1, 2, 1, 2 }
We cannot balance these teams evenly. We can come close by assigning the first and third players to the first team. The first team's score will then be 7 and the second team's score will be 6.
3)
    
{300,300,300,300}
{600,10,10,10}
Returns: {2, 1, 1, 2 }
4)
    
{50,50,50,1}
{30,30,30,150}
Returns: {1, 2, 2, 1 }
Teams must be of equal size.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

StampsCollection

Dynamic Programming, Graph Theory



Used in:

SRM 418

Used as:

Division I Level Two

Writer:

Rydberg

Testers:

PabloGilberto , Olexiy , Mike Mirzayanov , ivan_metelsky , darnley

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9886

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13509&pm=9886

Problem Statement

    You have decided to sell your stamp collection, which consists of n stamps numbered 0 to n-1. You have already found some buyers. The i-th buyer wants to buy the stamps listed in demand[i]. This will be a space-separated list containing either one or two stamps. He is willing to pay a total of price[i]. If he wants to buy two stamps, he will not agree to buy only one of them.



To make this task simpler, for each stamp, there will be no more than two buyers who want to buy it. Return the maximum amount of money you can get from selling your stamps.
 

Definition

    
Class:StampsCollection
Method:sell
Parameters:int, String[], int[]
Returns:int
Method signature:int sell(int n, String[] demand, int[] price)
(be sure your method is public)
    
 

Notes

-You don't have to sell all of your stamps.
 

Constraints

-n will be between 1 and 50, inclusive.
-demand will contain between 1 and 50 elements, inclusive.
-price will contain the same number of elements as demand.
-Each element of demand will be a space-separated list of one or two distinct integers.
-All numbers in demand will be between 0 and n-1, inclusive, with no leading zeroes.
-All numbers in price will be between 1 and 1000000, inclusive.
-For each stamp, there will be at most 2 buyers who want to buy it.
 

Examples

0)
    
10
{"0 4"}
{3}
Returns: 3
There is only one buyer, so all we can do is to sell two stamps.
1)
    
2
{"1 0","0"}
{3,5}
Returns: 5
There are two buyers, but both want to buy stamp 0.
2)
    
3
{"0 1","0 2","1 2"}
{10,11,12}
Returns: 12
Only one buyer can get what he wants - we choose the third one, who is willing to pay the most.
3)
    
3
{"0","1 0","1 2"}
{5,9,5}
Returns: 10
Although the second buyer will pay the most, it is better to choose the first and third buyers.
4)
    
20
{"0 1","1 2","2 3","3 0","4 5","5 6","6 4","8","8","9","9 10","10 11","11 12","12"}
{3,7,4,1,3,3,1,5,6,5,18,10,1,5}
Returns: 40

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ColoringRectangles

Geometry, Greedy, Simple Math



Used in:

TCHS SRM 60

Used as:

Division I Level Three

Writer:

boba5551

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9858

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13529&pm=9858

Problem Statement

    

You are given several rectangles in the Cartesian plane with sides parallel to the axes. They are represented by the int[]s x1, y1, x2 and y2, where (x1[i], y1[i]) are the coordinates of the lower-left corner and (x2[i], y2[i]) are the coordinates of the upper-right corner of the i-th rectangle.

Your task is to color exactly K rectangles in such a way that the visible colored area is as large as possible. If some area is covered by more than one rectangle, only the part of the rectangle with the highest index is visible (see example 0). Return a int[] containing exactly K elements - the 0-based indices of the colored rectangles. If there are several possible return values, return the one that comes earliest lexicographically. A int[] a1 comes before a int[] a2 lexicographically if a1 has a smaller element at the first index where they differ.

 

Definition

    
Class:ColoringRectangles
Method:maxColoredArea
Parameters:int[], int[], int[], int[], int
Returns:int[]
Method signature:int[] maxColoredArea(int[] x1, int[] y1, int[] x2, int[] y2, int K)
(be sure your method is public)
    
 

Constraints

-x1 will contain between 1 and 50 elements, inclusive.
-x1, y1, x2 and y2 will all contain same number of elements.
-Each element of x1, x2, y1 and y2 will be between -10000 and 10000, inclusive.
-x1[i] will be strictly less than x2[i] for all i.
-y1[i] will be strictly less than y2[i] for all i.
-K will be between 1 and number of elements in x1, inclusive.
 

Examples

0)
    
{1, 3, 2}
{1, 2, 5}
{5, 7, 9}
{3, 4, 7}
2
Returns: {1, 2 }
If you color rectangles with indices 0 and 1, the visible colored area will be 6 + 8 = 14.

If you color rectangles with indices 0 and 2, the visible colored area will be 6 + 14 = 20.

If you color rectangles with indices 1 and 2, the visible colored area will be 8 + 14 = 22.



1)
    
{1, 2, 4, 7, 1, 6, 2}
{1, 2, 0, 1, 5, 5, 5}
{5, 4, 6, 9, 4, 9, 8}
{4, 3, 2, 4, 7, 7, 6}
4
Returns: {0, 2, 3, 6 }
2)
    
{-5646, -5814, -1459, 6522, -6564, 1450, -2132, 6911, -9062}
{1463, 2872, -5496, 5163, -8549, -7835, 4725, 2420, 6350}
{471, -626, -1110, 7374, 5856, 3365, 1934, 7775, 3495}
{5776, 4869, 7008, 8802, -1730, -7161, 8571, 8905, 7573}
2
Returns: {4, 8 }
3)
    
{-3591, 1138, -4086, -9022, 4306, -5936, 8559, -6010, 9427, 3327, -4508, 6444, -4004, 
-3183, -7990, -1338, -4241, -5417, 1057, -8444, -9621, 4001, -4373, -6506, -1068, -5504}
{347, -1456, 117, -5894, -9053, -762, 6132, -9380, 3501, -8102, -2173, -271, -6271, 
-7546, -4792, -4591, -9430, 1185, -914, -5802, -1424, -9786, -3138, 1433, -9060, 2509}
{7239, 4410, 7929, -2195, 6088, 8953, 8700, -1599, 9886, 8966, -3672, 7583, -1242, 
1923, 9511, 3815, -3549, 7758, 1323, 1730, -1868, 5412, 727, 8930, 6211, -4513}
{6643, 7598, 4989, 3169, 1833, 4242, 8541, 8428, 5596, -2838, 2957, 1326, -5883, 
1850, 7082, 9761, -6129, 4223, 8920, -5237, 992, -5976, 2830, 4338, -8927, 6236}
15
Returns: {3, 7, 9, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25 }
4)
    
{-1, 2, -2, 2}
{-5, 2, 3, -4}
{1, 5, 1, 6}
{1, 6, 7, -1}
3
Returns: {0, 1, 2 }
All rectangles are of equal size and no two of them are overlapping.




This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RussianCheckers

Recursion, Simulation



Used in:

SRM 416

Used as:

Division I Level Three

Writer:

xOberon

Testers:

PabloGilberto , Olexiy , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9857

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13507&pm=9857

Problem Statement

    

Russian Checkers is a game played on an 8x8 board of alternating dark and light squares. The square in the lower-left corner is dark, and only dark squares are used in the game. Columns are labelled 'a' to 'h' from left to right, and rows are labelled '1' to '8' from bottom to top. Each cell is denoted by its column followed by its row (for example, "a4" or "f8"). The following image shows an empty board:

There are two players taking alternate turns. One player controls the white pieces and the other controls the black. The white player sits at the bottom of the board and the black player sits at the top. Every piece is exactly in one of the two types: "man" and "king".

There are two types of moves - a simple move and a capturing move. The player can make a simple move in his turn only if there are no available capturing moves for him in this turn.

A simple move for a "man" consists of moving diagonally forward to an adjacent empty square. White pieces move forward by moving to higher numbered rows, and black pieces move forward by moving to lower numbered rows. The following image shows four possible simple moves:

A capturing move for a "man" consists of jumping over a diagonally adjacent opponent piece (this piece is considered to be captured) and landing in the empty square immediately beyond that piece. After landing, if another capture is possible from that new square, it must be performed as part of the same turn. This can happen multiple times within the same turn. If multiple captures are possible from a position, any one of them can be performed. When capturing, pieces can move in any of the four diagonal directions, and can change directions after each landing. After the end of a capturing move all captured pieces are removed from the board. It is not allowed to capture the same opponent piece more than once during the same turn. The image below shows two possible capturing moves - c3 to e5 to c7, and c3 to e5 to g3. Note that, for example, the capturing move c3 to e5 to g3 to e5 to c7 is not valid because it requires jumping two times over the piece at f4.

When a "man" reaches the far side of the board (row 8 for white pieces, and row 1 for black pieces), it is promoted to a "king". A "king" moves differently than a "man". A simple move for a "king" consists of moving one or more squares in any of the four diagonal directions. All the squares in the path, including the ending square, must be empty.

A capturing move for a "king" consists of moving zero or more squares diagonally, jumping over an opponent piece, and then moving zero or more additional squares along the same path. With the exception of the square containing the jumped opponent piece, all squares in the path must be empty, and the path must form a straight diagonal line. When the "king" moves zero or more additional squares after jumping over the opponent, it must stop at a square from which it can perform another capture if possible. If there are multiple such squares, any one of them can be chosen. If there are no such squares, it can stop at any empty square. The "king" must continue making captures within the same turn as long as possible captures exist. As with "men", all captured pieces are removed from the board after the end of move, and it is not allowed to capture the same opponent piece more than once during the same turn. The following image shows the three possible moves a white king can make in a single turn - a1 to e5 to c7, a1 to e5 to b8, and a1 to f6 to d8:

If a "man" reaches the far side of the board as the result of a capturing move, it becomes a "king" and must continue capturing if possible, but as a "king". The following image shows a white "man" jumping a black piece, becoming a "king", and continuing to capture as a "king":

Your task is to write the first part of an AI engine. Given the current configuration of the board, and the player with the current turn, you must determine all the possible moves for that player. The board will be given in the String[] board, the first element of which describes row 8 from left to right, the second element of which describes row 7 from left to right, etc. '.' characters denote empty cells, 'b' and 'w' denote black and white "men", respectively, and 'B' and 'W' denote black and white "kings", respectively. The current player is given in the String turn, and will be either "BLACK" or "WHITE" (quotes for clarity). Return a String[] containing all the possible moves for the current player in lexicographical order. Each move is described by the sequence of cells in which the piece lands, starting with the piece's original position. In a simple move, cells are separated by '-' characters, and in a capturing move, cells are separated by ':' characters. See examples for further clarification.

 

Definition

    
Class:RussianCheckers
Method:listMoves
Parameters:String[], String
Returns:String[]
Method signature:String[] listMoves(String[] board, String turn)
(be sure your method is public)
    
 

Notes

-It is possible that the position described by board can never occur in real life. For example in a real Russian checkers game there will never be more than 12 pieces for each side, but in our game it is possible.
-A String A is lexicographically less than a String B if A is a prefix of B, or if, for some character at index i, A[i] < B[i], and for all j < i, A[j] = B[j].
 

Constraints

-board will contain exactly 8 strings.
-Each element of board will contain exactly 8 characters long.
-Each character in board will be one of {'.', 'w', 'W', 'b', 'B'}.
-board will contain '.' in cells that correspond to light board cells.
-turn will be either "BLACK" or "WHITE" (quotes for clarity).
-The first element of board will not contain lowercase 'w'.
-The last element of board will not contain lowercase 'b'.
 

Examples

0)
    
{".b.b.b.b",
 "b.b.b.b.",
 ".b.b.b.b",
 "........",
 "........",
 "w.w.w.w.",
 ".w.w.w.w",
 "w.w.w.w."}
"WHITE"
Returns: {"a3-b4", "c3-b4", "c3-d4", "e3-d4", "e3-f4", "g3-f4", "g3-h4" }
This is the starting game position, and there are 7 distinct legal moves.
1)
    
{".......B",
 "......w.",
 "........",
 "........",
 ".......W",
 "........",
 "...W.W..",
 "........"}
"BLACK"
Returns: {"h8:c3:e1:g3", "h8:d4:g1" }
Note that the black "king" must capture the white piece at g7 and then continue capturing more pieces. There are two alternatives for the second piece it captures - it can capture either d2 or f2. If it captures d2, it must capture f2 next. If it captures f2, the turn is over. Note that cells in capturing moves are separated with ':'.
2)
    
{"........",
 "........",
 "...b....",
 "........",
 "...b.b..",
 "..w.....",
 ".....w..",
 "........"}
"WHITE"
Returns: {"c3:e5:c7", "c3:e5:g3" }
Note that simple moves for the piece at f2 are not allowed because capturing moves exist for the piece at c3.
3)
    
{"........",
 "..b.....",
 ".w......",
 "......B.",
 "........",
 "........",
 "........",
 "........"}
"WHITE"
Returns: {"b6:d8:h4" }
The last picture in the problem description. A white "man" jumps over a black piece, becoming a "king", and continues to capture as a "king".
4)
    
{"........",
 "......b.",
 "........",
 "........",
 "...W....",
 "........",
 ".b......",
 "........"}
"WHITE"
Returns: {"d4:a1", "d4:h8" }
Jumping over the same opponent piece more than once during one capturing move is prohibited.
5)
    
{"........",
 "..w.w...",
 "........",
 "....w...",
 "........",
 "..B.w...",
 "........",
 "........"}
"BLACK"
Returns: {"c3:f6:d8:b6:f2", "c3:f6:d8:b6:g1" }
But visiting the same free cell more than once during one capturing move is allowed. In this case, the black "king" visits cell d4 twice.
6)
    
{".......b",
 "....w.w.",
 "........",
 "....b...",
 ".w.w.w..",
 "........",
 "...w.w..",
 "........"}
"BLACK"
Returns: 
{"e5:c3:a5",
"e5:c3:e1:g3:d6:a3",
"e5:c3:e1:g3:d6:f8:h6",
"e5:c3:e1:h4:d8",
"e5:g3:e1:c3:a5",
"e5:g3:e1:c3:f6:d8",
"h8:f6:d8" }
In this situation, there are lots of choices for capturing moves.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TreeCount

Dynamic Programming



Used in:

SRM 413

Used as:

Division I Level Three

Writer:

yuhch123

Testers:

PabloGilberto , legakis , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9844

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13504&pm=9844

Problem Statement

    

In graph theory, an independent set or stable set is a set of vertices in a graph such that no two of the vertices are adjacent. That is, it is a set V of vertices such that for every two vertices in V, there is no edge connecting the two.

Similarly, we can define a k-stable set as a set of vertices in a graph such that each vertex in the set has at most k adjacent vertices that are also in the set. So the 0-stable set is the original stable set.

You will be given a String[] graph, representing an undirected, acyclic, connected graph. The j-th character of the i-th element of graph will be 'Y' if vertices i and j are connected, or 'N' otherwise. Return a int[] containing exactly n elements, where n is the number of elements in graph. The i-th element should be the number of distinct i-stable sets in the graph modulo 112901989, where i is a 0-based index.

 

Definition

    
Class:TreeCount
Method:count
Parameters:String[]
Returns:int[]
Method signature:int[] count(String[] graph)
(be sure your method is public)
    
 

Constraints

-graph will contain between 1 and 50 elements, inclusive.
-Each element of graph will contain exactly N characters, where N is the number of elements in graph.
-Each character in graph will be either 'Y' or 'N'.
-The j-th character of the i-th element of graph will equal to the i-th character of the j-th element.
-The i-th character of the i-th element of graph will be 'N'.
-The graph will represent a tree.
 

Examples

0)
    
{"NYY", "YNN", "YNN"}
Returns: {5, 7, 8 }
The tree is 1-0-2. The 5 0-stable sets are {}, {0}, {1}, {2}, {1, 2}. The 7 1-stable sets are all the subsets except {0, 1, 2}. There are 2^3 subsets total, and each one is a 2-stable set.
1)
    
{"N"}
Returns: {2 }
2)
    
{"NYNNNYY", "YNNNNNN", "NNNNNNY", "NNNNNNY", "NNNNNNY", "YNNNNNN", "YNYYYNN"}
Returns: {44, 73, 104, 124, 128, 128, 128 }
3)
    
{"NY", "YN"}
Returns: {3, 4 }
4)
    
{"NYYYYY", "YNNNNN", "YNNNNN", "YNNNNN", "YNNNNN", "YNNNNN"}
Returns: {33, 38, 48, 58, 63, 64 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RoadsOfKingdom

Graph Theory, Math



Used in:

SRM 425

Used as:

Division I Level Three

Writer:

crazyb0y

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9834

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13516&pm=9834

Problem Statement

    

Long long ago, there was a kingdom named Kingdom C. There were n cities in Kingdom C, and every pair of cities was connected by a two-way road. Unfortunately, some of those roads may have been destroyed in a heavy rain.

You are given a String[] roads. The probability that the road connecting city i and city j is still available after the heavy rain is d/8, where d is the j-th digit of the i-th element of roads.

The king of Kingdom C is very sad, and he wants to know the probability of the following scenario: Every city is reachable from the capital (city 0), but if you were to destroy any one of the remaining roads, there would be at least one city that is not reachable from the capital. Return the probability of this scenario as a double.

 

Definition

    
Class:RoadsOfKingdom
Method:getProbability
Parameters:String[]
Returns:double
Method signature:double getProbability(String[] roads)
(be sure your method is public)
    
 

Notes

-Your return must have relative or absolute error less than 1E-9.
 

Constraints

-roads will contain exactly n elements, where n is between 2 and 16, inclusive.
-Each element of roads will contain exactly n characters.
-All characters in roads will be between '0' and '8', inclusive.
-Character i in element i of roads will be '0'.
-Character i in element j of roads will be the same as character j in element i of roads.
 

Examples

0)
    
{"04",
 "40"}
Returns: 0.5
There is exactly one road connecting the capital and city 1. The answer is equal to the probability that the road is available after the rain.
1)
    
{"08",
 "80"}
Returns: 1.0
The same example as above, but this time the road is always available.
2)
    
{"00",
 "00"}
Returns: 0.0
In this case, all roads have been destroyed.
3)
    
{"088",
 "808",
 "880"}
Returns: 0.0
Here all three roads 0-1, 0-2 and 1-2 are definitely not destroyed. These roads form a cycle, so you can always remove a road in such way that all cities are reachable from the capital.
4)
    
{"044",
 "404",
 "440"}
Returns: 0.375
Exactly two of three roads should be available, so the probability is C(3,2) * 0.5^3 = 0.375.
5)
    
{"0701",
 "7071",
 "0708",
 "1180"}
Returns: 0.622314453125

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TeleportsNetwork

Brute Force, Graph Theory



Used in:

SRM 409

Used as:

Division II Level Three

Writer:

slex

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9830

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12181&pm=9830

Problem Statement

    

The Kingdom of Byteland has a big capital city that is the center of its industry and social life. To connect every city to the capital, the King decided to develop a network of roads. Each city, except for the capital, was responsible for building a single bidirectional road from itself to another city. For each city X, the following algorithm was used to determine the destination of the road built by that city:

  • Measure the Euclidean distances from all the cities to the capital, and consider only those which are strictly closer to the capital than city X (include the capital in that list).
  • If there is more than 1 city, pick the city which is closest to city X.
  • If there are multiple such cities, pick the city among them with the smallest X coordinate.
  • If there are still multiple such cities, pick the city among them with the smallest Y coordinate.

After all the roads were built, some people started to complain that they had to go through too many other cities to get to the capital. The King decided to construct teleportCount teleports to solve this problem. Each teleport would provide an instant connection between the city where it is placed and the capital.

Let's define the inconvenience of a city as the minimal number of roads one needs to follow to get from that city to the capital, or to a city with a teleport. For example, the inconvenience of the capital, and of all cities with teleports, is 0. The inconvenience of a city that doesn't have a teleport but is directly connected to the capital or to a city with a teleport is 1, and so on. Note that the shortest route from a city to the capital may involve traveling further away from the capital to reach a teleport.

The inconvenience of the whole Kingdom is the maximum inconvenience among its cities.

You are given int[]s citiesX and citiesY, where (citiesX[i], citiesY[i]) are the coordinates of the i-th city.The 0-th city is the capital. Distribute teleportCount teleports in such a way that minimizes the inconvenience of the Kingdom and return that minimum inconvenience value.

 

Definition

    
Class:TeleportsNetwork
Method:distribute
Parameters:int, int[], int[]
Returns:int
Method signature:int distribute(int teleportCount, int[] citiesX, int[] citiesY)
(be sure your method is public)
    
 

Notes

-The algorithm described in the problem statement guarantees that all the cities will be connected to the capital.
 

Constraints

-citiesX will contain between 1 and 50 elements, inclusive.
-teleportCount will be between 0 and 4, inclusive and less than the number of elements in citiesX.
-Each element of citiesX will be between 0 and 1000000, inclusive.
-citiesY will contain the same number of elements as citiesX.
-Each element of citiesY will be between 0 and 1000000, inclusive.
-No two cities will occupy the same point.
 

Examples

0)
    
2
{0,1,1,1,2,2}
{1,0,1,2,0,2}
Returns: 1
The network of roads will look like this:
     3--5
     |
  0--2
     |
     1--4
If we place teleports in cities 1 and 3, no city would have an inconvenience greater than 1.
1)
    
1
{0,1,1,1,2,2}
{1,0,1,2,0,2}
Returns: 2
The cities are located in the same places as in the previous example, but now there is only one teleport. It's best to place it in city 2.
2)
    
0
{0,1,1,1,2,3,3,4}
{1,1,2,0,0,0,2,1}
Returns: 5
     2-----6
     |      
  0--1       7
     |      /
     3--4--5
Cities 5 and 6 have the same distance to 7 and the same X coordinate, but 5 has a lower Y coordinate and that's why the road was built from 7 to 5.
3)
    
1
{0,1,2,3,4}
{0,0,0,0,0}
Returns: 1
0--1--2--3--4
The best solution is to place the teleport in city 3.
4)
    
4
{64,200,384,294,175,107,303,374,224,220,223,99,442}
{79,161,83,281,344,217,184,336,431,262,75,474,257}
Returns: 1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CorporationSalary

Graph Theory



Used in:

SRM 407

Used as:

Division I Level One , Division II Level Two

Writer:

Gluk

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9824

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12179&pm=9824

Problem Statement

    You are working in the HR department of a huge corporation. Each employee may have several direct managers and/or several direct subordinates. Of course, his subordinates may also have their own subordinates, and his direct managers may have their own managers. We say employee X is a boss of employee Y if there exists a sequence of employees A, B, ..., D, such that X is the manager of A, A is the manager of B, and so on, and D is the manager of Y (of course, if X is a direct manager of employee Y, X will be a boss of employee Y). If A is a boss of B, then B can not be a boss of A. According to the new company policy, the salary of an employee with no subordinates is 1. If an employee has any subordinates, then his salary is equal to the sum of the salaries of his direct subordinates.

You will be given a String[] relations, where the j-th character of the i-th element is 'Y' if employee i is a direct manager of employee j, and 'N' otherwise. Return the sum of the salaries of all the employees.
 

Definition

    
Class:CorporationSalary
Method:totalSalary
Parameters:String[]
Returns:long
Method signature:long totalSalary(String[] relations)
(be sure your method is public)
    
 

Constraints

-relations will contain between 1 and 50 elements, inclusive.

-Each element of relations will contain the same number of characters, which is equal to number of elements in relations.

-Each element of relations will contain only 'Y' or 'N'.

-Character i of element i of relations will be 'N' for each i.

-If A is a boss of B, then B will not be a boss of A.
 

Examples

0)
    
{"N"}
Returns: 1
Here we've got only one employee so the answer is 1.
1)
    
{"NNYN",
 "NNYN",
 "NNNN",
 "NYYN"}
Returns: 5
There are 4 employees here. 0, 1 and 3 are managers of 2, and also 3 is a manager of 1. So:

salary(2) = 1

salary(0) = salary(2) = 1

salary(1) = salary(2) = 1

salary(3) = salary(2) + salary(1) = 2
2)
    
{"NNNNNN",
 "YNYNNY",
 "YNNNNY",
 "NNNNNN",
 "YNYNNN",
 "YNNYNN"}
Returns: 17
3)
    
{"NYNNYN",
 "NNNNNN",
 "NNNNNN",
 "NNYNNN",
 "NNNNNN",
 "NNNYYN"}
Returns: 8
4)
    
{"NNNN",
 "NNNN",
 "NNNN",
 "NNNN"}
Returns: 4

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LockedDoors

Graph Theory, Search



Used in:

TCHS SRM 53

Used as:

Division I Level Three

Writer:

Nickolas

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9803

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13486&pm=9803

Problem Statement

    You are placed in a maze represented by a rectangular board. Each cell of the board can be one of the following:
  • empty: is always passable (represented by a '.')
  • a wall: is never passable (a '#')
  • a key: is always passable; when you enter it for the first time, you pick up the key (a lowercase letter 'a'-'f')
  • a door: is passable only if you have a corresponding key (an uppercase letter 'A'-'F')
  • your starting position: an empty cell where you are placed at the beginning (a '0' digit)
  • exit point: an empty cell you must enter to get out of the maze (a '1' digit).
You must get out of the maze using a minimal number of moves. In one move you can get to a cell which is adjacent to your current position vertically or horizontally.

You will be given a String[] maze. Each character in maze will represent a single cell of the maze. A key denoted with a certain lowercase letter opens the door denoted with the corresponding uppercase letter only. Return the minimal number of moves that will bring you to an exit point. There can be several exit points, in which case you can get to any of them. If you can't get to any exit point, return -1.
 

Definition

    
Class:LockedDoors
Method:pathOutside
Parameters:String[]
Returns:int
Method signature:int pathOutside(String[] maze)
(be sure your method is public)
    
 

Notes

-It is possible to have several keys or several doors of the same type on the map.
-It is possible to have a door without the corresponding key, and vice versa.
-Once you have picked up a key, you can use it multiple times.
 

Constraints

-maze will contain between 1 and 50 elements, inclusive.
-Each element of maze will contain between 1 and 50 characters, inclusive.
-All elements of maze will contain the same number of characters.
-Each character in maze will be '.', '#', '0' (digit), '1' (digit), 'A'-'F' or 'a'-'f'.
-There will be exactly one '0' character and at least one '1' character in maze.
 

Examples

0)
    
{"1..0",
 "###.",
 "1..."}
Returns: 3
There are no keys or doors in the maze.
1)
    
{"..0..",
 ".###.",
 "..1.A"}
Returns: 6
We can get to the exit without opening the door.
2)
    
{"f0.F..1"}
Returns: 7
3)
    
{"0....",
 ".#B#A",
 ".#.#.",
 "b#a#1"}
Returns: 19
You have to get the 'b' key first, open the 'B' door, get the 'a' key and open the 'A' door to get to the exit.
4)
    
{"c.0.C.C.C.1"}
Returns: 12
The 'c' key opens all 'C' doors.
5)
    
{"###...",
 "#0A.1a",
 "###..."}
Returns: -1
6)
    
{"a#c#eF.1",
 ".#.#.#..",
 ".#B#D###",
 "0....F.1",
 "C#E#A###",
 ".#.#.#..",
 "d#f#bF.1"}
Returns: 55
You have to get all 6 keys in the correct order to open the 'F' door.
7)
    
{"0abcdef.FEDCBA1"}
Returns: 14
You can carry several types of keys at once.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TournamentSeeding

Greedy



Used in:

SRM 408

Used as:

Division I Level Three

Writer:

connect4

Testers:

PabloGilberto , Olexiy , Andrew_Lazarev , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9802

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12180&pm=9802

Problem Statement

    

The Total Conquest soccer league is about to begin its season ending tournament next week. The tournament will be a single elimination tournament, meaning that a team that loses is immediately eliminated from the tournament. To set up the tournament, each team will be assigned a unique seed prior to the start of the tournament (starting from 0); the number of teams in the tournament will be a power of 2. The following algorithm in pseudocode is then used to determine pairings:

SetSeeds(String[] Teams)
{
	LET N = the number of teams left
	IF(N==1) 
		The tournament is over
	ELSE
		Pair all teams such that their seeds sum to N-1.
		Assume the lower seeded team wins each game.
		Call SetSeeds(Winners)
}

For example, in an 8 team tournament, the first round games would be between 0-7, 1-6, 2-5, and 3-4. In the second round, the games would be between 0-3 and 1-2, with the winners meeting in the final.

Due to the format of the tournament, it is possible for a second round game to be played before all first round games have finished; a game may be started as long as both teams have advanced to the correct round. In the above tournament, for instance, if teams 0 and 3 win their opening round games, they may play their second round game prior to the game between 2-5.

You have been given a list of the teams in the tournament; you should concatenate the elements of teams to form a single space separated list of teams in the tournament with no leading or trailing spaces. You also will be given games; this should be concatenated to form a single space separated list representing the games played. Each game will be represented by two words; the first will be the name of the winning team, and the second will be the team that lost that game. The games may be listed in any order, but all games that have been played in the tournament so far will be listed.

You know that all games played in the tournament will be won by the team with the lower numbered seed. Assign the seeds to teams consistent with the games played; if there is more than one way to do this, select the lexicographically first among them (see Notes). Return a String[] containing the same number of elements as seeds; the i-th element in the return should correspond to the team name of the team that has been assigned seed seeds[i]. If the games listed in games do not represent a valid set of games in a tournament, return an empty String[].

 

Definition

    
Class:TournamentSeeding
Method:getSeeds
Parameters:String[], String[], int[]
Returns:String[]
Method signature:String[] getSeeds(String[] teams, String[] games, int[] seeds)
(be sure your method is public)
    
 

Notes

-An assignment of teams A is lexicographically earlier than B if, for some seed i, A[i] < B[i], and for all seeds j < i, A[j]=B[j].
-When comparing two Strings, digits ('0'-'9') come before letters.
-A String C is less than D if C is a prefix of D, or if, for some character at index i, C[i] < D[i], and for all j < i, C[j]=D[j].
 

Constraints

-teams will contain between 1 and 50 elements, inclusive.
-Each element of teams will contain between 1 and 50 characters, inclusive.
-teams will contain only uppercase letters ('A'-'Z'), digits ('0'-'9') and spaces (' ').
-The number of teams listed in teams will be a non-negative power of 2.
-There will be no duplicate team names in teams.
-teams will be formatted as described in the statement.
-Each name in teams will contain between 1 and 20 characters, inclusive.
-games will contain between 0 and 50 elements, inclusive.
-Each element of games will contain between 1 and 50 characters, inclusive.
-When concatenated, games will contain a single space separated list of names from teams, with no leading or trailing spaces.
-When concatenated, games will contain an even number of team names.
-No team will play against itself in games.
-There will be no repeated game listed in games.
-seeds will contain between 1 and 50 elements, inclusive.
-Each element of seeds will be between 0 and N-1, inclusive, where N is the number of teams in teams.
 

Examples

0)
    
{"CELTICS ", "LAKER", "S SPURS PISTONS"}
{"CELTICS LAKERS CELTICS PISTONS LAKERS SPURS"}
{0, 1, 2, 3}
Returns: {"CELTICS", "LAKERS", "SPURS", "PISTONS" }
The final rounds of the 2008 NBA playoffs. The first round games were CELTICS-PISTONS and LAKERS-SPURS, and the CELTICS beat the LAKERS in the final.
1)
    
{"GIANTS PATRIOTS CHARGERS PACKERS"}
{"PATRIOTS CHARGERS"}
{3, 2, 1, 0}
Returns: {"PACKERS", "CHARGERS", "PATRIOTS", "GIANTS" }
Here is an incomplete tournament with only one game played. There are several possible seedings, but the lexicographically earliest seeding is:
0) GIANTS
1) PATRIOTS
2) CHARGERS
3) PACKERS
2)
    
{"REDSOX PHILLIES METS DODGER",
 "S ORIOLES BLUEJAYS CUBS AN",
 "GELS"}
{"METS ANGELS",
 " METS CU",
 "BS ORIO",
 "LES ANGELS"}
{0, 1, 2, 3, 4, 5, 5, 5}
Returns: { }
In a single elimination tournament, it is impossible for the ANGELS to lose twice.
3)
    
{"REDSOX PHILLIES METS DODGER",
 "S ORIOLES BLUEJAYS CUBS AN",
 "GELS"}
{"METS ANGELS",
 " METS CU",
 "BS CU",
 "BS DODGERS REDSOX PHILLIES"}
{0, 1, 2, 3, 4, 5, 6, 7}
Returns: 
{"BLUEJAYS",
"METS",
"CUBS",
"REDSOX",
"PHILLIES",
"DODGERS",
"ANGELS",
"ORIOLES" }
In this tournament, the second round game between the METS and CUBS was played before the BLUEJAYS-ORIOLES game from the first round.
4)
    
{"A B C D E F 8 H I 3 9 L 4 N O P"}
{"P A B H D C D E E N"}
{0, 2, 0, 0, 3, 4, 7, 2}
Returns: {"3", "8", "3", "3", "D", "E", "P", "8" }
Note that the same seed may be requested multiple times.
5)
    
{"A B C D E F G H"}
{"A B C D A C E F"}
{0, 1, 2, 3, 4, 5, 6, 7}
Returns: {"A", "E", "G", "C", "D", "H", "F", "B" }
6)
    
{"NEWYORKISLANDERS"}
{}
{0}
Returns: {"NEWYORKISLANDERS" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TransformMatrix

Graph Theory



Used in:

SRM 407

Used as:

Division I Level Three

Writer:

Gluk

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9790

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12179&pm=9790

Problem Statement

    You are given two matrices A and B. Each matrix is represented by a String[] containing only '0' and '1' digits. The j-th character of the i-th element is the value at cell (i, j). Your goal is to transform matrix A into matrix B using a series of swaps. On each swap, you choose two adjacent (horizontally, vertically or diagonally) cells in matrix A and swap their values.

There is a limit to the number of times each cell in matrix A can be used. You are given a third matrix count as a String[] containing only digits ('0'-'9'). Cell (i, j) in matrix A can be used in a maximum of count(i, j) swaps. Return the fewest number of swaps required to achieve your goal, or return -1 if it is impossible.
 

Definition

    
Class:TransformMatrix
Method:transform
Parameters:String[], String[], String[]
Returns:int
Method signature:int transform(String[] A, String[] B, String[] count)
(be sure your method is public)
    
 

Constraints

-A will contain between 1 and 20 elements, inclusive.

-A, B and count will contain the same number of elements.

-Each element of A, B and count will contain between 1 and 20 digits, inclusive.

-Each element of A, B and count will contain the same number of characters.

-Each element of count will contain only digits ('0' to '9').

-Each element of A and B will contain only '0' (zero) and '1' (one) digits.
 

Examples

0)
    
{"110", 
 "000",
 "001"}
{"000",
 "110",
 "100"}
{"222",
 "222",
 "222"}
Returns: 4
Here is one of the ways:

(0,0) - (1,1)

(0,1) - (1,0)

(2,2) - (2,1)

(2,1) - (2,0)
1)
    
{"10"}
{"01"}
{"11"}
Returns: 1
Just swap the values in the two cells of the matrix.
2)
    
{"111",
 "000",
 "111"}
{"111",
 "000",
 "111"}
{"013",
 "537",
 "136"}
Returns: 0
Matrix A is already equal to matrix B, so no swaps are required.
3)
    
{"001",
 "110"}
{"000",
 "111"}
{"000",
 "111"}
Returns: -1
Here we can't use any cell from row 0.
4)
    
{"100",
 "000"}
{"000",
 "000"}
{"999",
 "999"}
Returns: -1
The two matrices contain a different number of '1's, so it is impossible to transform one into the other.
5)
    
{"011101",
 "110000",
 "000011",
 "000000",
 "100000"}
{"110100",
 "000011",
 "000000",
 "110001",
 "000010"}
{"305713",
 "537211",
 "352421",
 "242212",
 "333313"}
Returns: 10
6)
    
{"10",
 "00"}
{"00",
 "01"}
{"11",
 "11"}
Returns: 1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AllCycleLengths

Graph Theory, String Manipulation



Used in:

SRM 405

Used as:

Division I Level Two

Writer:

Petr

Testers:

PabloGilberto , Olexiy , Jan_Kuipers , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9764

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12177&pm=9764

Problem Statement

    

There are several cities in a country, and some pairs of those cities are connected by one-way roads (although it is possible that there are one-way roads both from A to B and from B to A). It is possible to get from any city to any other city using roads. A traveler starts from some city, and travels along one of the roads every day. A number x is called vacation-friendly if a traveler can have an x-day long vacation. That means he can start from some city, travel exactly x roads, and be back at the city where he started.

A vacation string is an infinite string of '0' and '1' digits, which has a '1' in the x-th (1-based) position if and only if x is a vacation-friendly number.

For example, consider the country shown in the following picture.



Its vacation string is "0011011111111...": 0->1->3->0 is a 3-day vacation, 0->1->2->3->0 is a 4-day vacation, 0->1->3->0->1->3->0 is a 6-day vacation, 0->1->2->3->0->1->3->0 is a 7-day vacation, and so on.

It turns out that every vacation string becomes periodic at some point. We will enclose the period in parentheses to obtain a finite representation for a vacation string. For example, the above vacation string can be represented by "00110(1)" or "00110111(11)". We will call the shortest possible representation canonical.

Given a description of a country as a String[] arcs, where the j-th character of the i-th element of arcs is 'Y' if there is a road from city i to city j, and 'N' otherwise, return the canonical representation of its vacation string.

 

Definition

    
Class:AllCycleLengths
Method:findAll
Parameters:String[]
Returns:String
Method signature:String findAll(String[] arcs)
(be sure your method is public)
    
 

Constraints

-arcs will contain between 2 and 30 elements, inclusive.
-Each element of arcs will contain exactly n characters, where n is the number of elements in arcs.
-Each character of each element of arcs will be either 'Y' or 'N'.
-The i-th character of the i-th element of arcs will always be 'N'.
-arcs will define a network of roads where it is possible to get from any city to any other city using the roads.
 

Examples

0)
    
{"NYNN", "NNYY", "NNNY", "YNNN"}
Returns: "00110(1)"
The example from the problem statement.
1)
    
{"NY", "YN"}
Returns: "(01)"
Only even numbers are vacation-friendly here.
2)
    
{"NYYYY", "NNYYY", "NNNYY", "NNNNY", "YNNNN"}
Returns: "0(1)"
Every vacation length except 1 is possible here.
3)
    
{"NYNNN", "NNYNN", "NNNYN", "NNNNY", "YNNYN"}
Returns: "010(1)"
The vacation can start from any vertex.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RelativePath

String Manipulation



Used in:

SRM 405

Used as:

Division I Level One , Division II Level Two

Writer:

Petr

Testers:

PabloGilberto , Olexiy , Jan_Kuipers , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9760

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12177&pm=9760

Problem Statement

    

In a typical filesystem, there are files, representing complete units of data. These files are contained in directories, and these directories, in turn, may be contained in other directories, and so on. A path is a pointer to a specific file or directory in this stucture. Most Unix-like OSes have a single root directory, that has all other directories and files directly or indirectly (via other directories) inside it. Such OSes use the following structure for file paths:

/<directory-name>/<directory-name>/.../<directory-name>/<file-name>

and, correspondingly, the following structure for directory paths:

/<directory-name>/<directory-name>/.../<directory-name>

For example, "/etc/passwd" (all quotes here and below are for clarity only) points to a file named "passwd" inside a directory named "etc" inside the root directory. Other valid file names might be "/home/user/pictures/me" or just "/file". In this problem, we allow only nonempty sequences of lowercase letters ('a'-'z') as file and directory names.

A special case is the root directory itself, which is referred to as just "/".

When a user works with such an OS, one of the directories is chosen as 'current'. Such a designation allows her to refer to the files in that directory without specifying the full path to the current directory. For example, if the current directory is "/home/user/pictures", then one might refer to the file "/home/user/pictures/me" as just "me" (note that such a short form can be easily spotted by the absence of the starting '/' character). Moreover, the files in subdirectories of the current directory can also be referred to in a short manner: "/home/user/pictures/others/she" can be referred to as "others/she".

And even more exciting is the ability to have short references for files outside the current folder. More specifically, ".." means "the directory one level above the current directory", "../.." means "the directory two levels above the current directory", and so on. For example, if the current directory is "/home/user/pictures", and you want to refer to "/home/top/data/file", you can express that as "../../top/data/file".

Given a String path, indicating the complete path to the file that needs to be referred to, and a String currentDir, indicating the current directory, return a String that contains the relative path to that file according to the above rules. You should choose the shortest of all possible relative paths (for example, if the current directory is "/home/user/pictures", you should use "../movies/title" and not "../../user/movies/title" as a pointer to "/home/user/movies/title").

Some files and/or directories may have coinciding names, but it is impossible to have two files or two directories or a file and a directory with the same name inside the same directory, so file and directory paths are not ambiguous. It is guaranteed that the given data describes a valid file and directory according to the above rules. In particular, they will not contradict - for example, path="/home/user/some" and currentDir="/home/user/some/other" are a contradiction, since it implies that a file and a directory both named "some" exist inside the directory "/home/user".

 

Definition

    
Class:RelativePath
Method:makeRelative
Parameters:String, String
Returns:String
Method signature:String makeRelative(String path, String currentDir)
(be sure your method is public)
    
 

Notes

-A file name never ends with the '/' character. A directory name never ends with the '/' character, with the exception of the root directory, which is specified as just "/".
 

Constraints

-path and currentDir will each contain between 1 and 50 characters, inclusive.
-Each character of path and currentDir will be '/', or a lowercase letter ('a'-'z').
-path will contain a valid file path according to the above rules.
-currentDir will contain a valid directory path according to the above rules.
-path and currentDir will not contradict (see the last paragraph of the statement).
 

Examples

0)
    
"/home/top/data/file"
"/home/user/pictures"
Returns: "../../top/data/file"
The example from the problem statement.
1)
    
"/home/user/movies/title"
"/home/user/pictures"
Returns: "../movies/title"
And another one from the statement.
2)
    
"/file"
"/"
Returns: "file"
Remember about the root directory.
3)
    
"/a/b/a/b/a/b"
"/a/b/a/a/b/a/b"
Returns: "../../../../b/a/b"
Some file and directory names may be the same.
4)
    
"/root/root/root"
"/root"
Returns: "root/root"
Some files and/or directories can be named "root" - but that doesn't make them root directories.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

UnknownNames

Brute Force, Simple Search, Iteration, Sorting, String Manipulation



Used in:

TC China 08 - Finals

Used as:

Division I Level Two

Writer:

boba5551

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9759

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13678&pm=9759

Problem Statement

    

You are given a String[] questionMarkNames, where each element represents a single name, and all names have the same length. Some of the letters are missing, and those letters are represented by question marks ('?'). Arrange the names in a vertical row, such that corresponding characters in each name are in the same column. Then, order the names so that each column is sorted in non-decreasing order from top to bottom. You can replace each question mark with any letter to achieve this.

Return a String[] containing the lexicographically earliest ordering that you can achieve. If there is no way to achieve the goal, return an empty String[] instead. An ordering A comes before an ordering B if A contains an alphabetically earlier name at the first index where they differ.

 

Definition

    
Class:UnknownNames
Method:sortNames
Parameters:String[]
Returns:String[]
Method signature:String[] sortNames(String[] names)
(be sure your method is public)
    
 

Constraints

-questionMarkNames will contain between 2 and 50 elements, inclusive.
-Each element of questionMarkNames will containt between 1 and 50 characters, inclusive.
-All elements of questionMarkNames will be of the same length.
-Each character of each element of questionMarkNames will be an uppercase letter ('A'-'Z') or a question mark ('?').
 

Examples

0)
    
{"?ED?", "TO??", "????"}
Returns: {"AAAA", "AEDA", "TODA" }
If we make the order of names
0 1 2
then the lexicographically earliest ordering is
AEDA
TODA
TODA

0 2 1
AEDA
AEDA
TOEA

1 0 2
TO??
TED?
T???
- IMPOSSIBLE for this order, because O is after E, etc.
1)
    
{"T???????", "SO??????", "?MP?????", "??OC????", "???BO???", "????MD??", "?????CE?", "??????CR"}
Returns: 
{"AAAAAACR",
"AAAAACER",
"AAAAMDER",
"AAABODER",
"AAOCODER",
"AMPCODER",
"SOPCODER",
"TOPCODER" }
2)
    
{ "?E", "L?", "??", "L?"}
Returns: {"AA", "AE", "LE", "LE" }
3)
    
{"A???J?", "BC????", "?DE???", "??FG??", "???HI?"}
Returns: { }
4)
    
{"AAH????AB?EE??GCB?HE?G?CACA?A?B??A?JG?AGD????F?EEE",
 "?D?NI??JK?H?N?K???HKM?L?GE?N??G?K?L??M?HM??CP?E?NJ",
 "?KOVL?????K??TKP???L??N?N??O????MI?Y?QK?NR?E?RF???",
 "?M?Z??N?T??R????????TP?OQ??SY??Z?O?Z?YTL?RMG???YV?",
 "W???????Z?TX?Z???XZMYRNX??L??Q?????????L?T?J????Z?",
 "ZYZZ?????S?ZZZ?Z??ZV?Y????LZ?R?ZZVZZ?Z??ZT?M?V?Z??",
 "?Y?Z?Z?X??UZ?ZZ??ZZY?ZV?Z?MZ?W?Z??Z?ZZ?????TZ??Z?Z",
 "Z?????Z??ZV????Z????Z?????S????ZZZZ????Z???TZ?W?ZZ",
 "ZZ??ZZZ???WZZZ????Z?Z?Z?Z???Z?Z?ZZ?Z??Z??Z?W???ZZ?",
 "??????????Z?Z?Z??Z?ZZZ?Z??ZZ?Z?????ZZ??ZZZZZ??ZZ??",
 "?Z?Z???Z????Z?ZZ??Z?ZZZ?Z???Z?ZZ??Z?Z??Z??Z??Z???Z",
 "?Z?ZZ?Z??ZZ?ZZ???????Z???ZZZ?Z?ZZ?Z?ZZ?Z?ZZZ?Z??ZZ",
 "??Z??ZZ?Z?ZZ?ZZ????Z???Z??Z???????Z??Z??Z???Z?ZZ?Z",
 "ZZ??Z?ZZ??ZZZ??Z????ZZ?Z?ZZ??ZZ???Z?ZZ??ZZZZZZZ??Z",
 "?Z????ZZZ???Z??Z?Z?Z?Z????Z??ZZZZ??ZZ?Z?????Z??Z??",
 "Z???ZZZ??Z?ZZ??Z??Z?Z???Z???ZZ??Z???Z?ZZ??ZZ??Z??Z",
 "??????ZZ???Z?Z?ZZ?ZZ????Z??Z??????ZZ?ZZ?Z?Z?Z??Z??",
 "ZZZ?Z??ZZ???Z??Z?Z?ZZ?Z??ZZ?Z????ZZZ??Z??Z?ZZ??ZZZ",
 "Z?Z???ZZZ???ZZ?Z??Z???ZZZZZ??Z??Z??Z?Z?ZZZ?ZZ??Z?Z",
 "Z???Z???ZZ?Z??Z??ZZ??ZZZ??Z??ZZ?Z?????????Z???Z?ZZ",
 "Z?Z????Z?ZZZ?????Z???Z?Z??ZZ??Z??ZZZ??ZZZ?Z?ZZ?Z?Z",
 "???Z?????????ZZZZ??Z?Z??Z????Z??ZZ???Z?ZZ??????Z??",
 "???Z?Z?ZZZ?Z??Z?????Z??????ZZZ?Z?Z?ZZ?ZZZZZ?ZZZZ??",
 "Z??ZZ??Z?????Z????ZZZ?Z?Z??Z?ZZZ?Z?Z???Z?Z??????Z?",
 "ZZ?Z?ZZ?Z???ZZ????Z???Z?Z??Z?ZZZZ??ZZZ???ZZ?Z?ZZZ?",
 "??ZZ????ZZ??Z?Z????ZZZ?Z?Z?Z?ZZZ?Z???ZZ?ZZ???Z???Z",
 "Z??Z???Z?ZZZ???Z?Z?????Z???ZZ???Z?ZZZ?????Z??ZZZ??",
 "?Z????ZZZ??Z???????Z???Z???Z?Z?Z??Z?ZZ?ZZ?ZZZZ???Z",
 "?ZZZ?ZZZZ?ZZ?Z?ZZZZ?ZZ?Z?Z??Z?ZZ??ZZ?Z???Z??????ZZ",
 "ZZ?ZZZ??Z????Z?ZZZZZ?Z???Z??ZZ?Z???ZZ?Z?Z?ZZ??ZZZZ",
 "?ZZ?Z?ZZ?ZZZ?ZZ??ZZZZ?ZZ?Z?Z?????ZZ???ZZZZ?Z?Z?ZZ?",
 "Z??ZZ??ZZ???Z?ZZZ??Z??ZZ?Z?Z??????Z?ZZ?ZZZZ?Z?Z??Z",
 "???ZZ???ZZZZZZ???????ZZZZZ?Z?Z?ZZZZZ??ZZZ??ZZZ????",
 "Z?ZZ?Z?ZZ???ZZZZZ???ZZ?ZZ?Z??ZZ?Z????Z??Z?????ZZ?Z",
 "??Z?ZZZ?Z???Z???Z?ZZ???Z??ZZ???Z??ZZ??Z???Z?????ZZ",
 "?Z?Z?Z?Z?Z?Z?ZZ???Z??ZZ?ZZZ?Z???????Z?ZZ?ZZ???????",
 "Z??Z??Z???ZZZZZZ??ZZ???????ZZZZ?Z?????ZZ?Z??Z??ZZ?",
 "????????Z??ZZ????ZZ??Z?ZZ???Z?ZZ??Z?Z??ZZZ?ZZZ?ZZ?",
 "??Z??ZZ?Z?Z?????Z??Z?ZZZ??Z?Z?ZZ??ZZ?Z?Z?ZZ???ZZ??",
 "??ZZ???ZZ????????ZZZZ????Z??ZZ?Z?Z?ZZZZZZZ????ZZ??",
 "?ZZ?Z????ZZ???ZZZ?Z???Z?ZZZ???Z?ZZZ?????ZZZZZ?Z?ZZ",
 "????Z?Z??Z????Z??ZZZZZ??Z??ZZZ?ZZ??Z???Z?Z?Z???ZZ?",
 "Z???????Z?ZZZZ??Z?ZZZ?ZZZ??Z??Z??Z?Z?ZZZ?Z?Z?ZZ?ZZ",
 "?Z?ZZ??ZZZZ???ZZZZZZZ?ZZ????Z?Z?ZZ???Z?Z?ZZ???Z??Z",
 "??Z?Z??Z?Z??ZZ??Z?ZZ?Z???ZZ??ZZ???Z?????Z?Z?ZZ?Z?Z",
 "Z?Z??ZZ???ZZ?ZZZ?ZZZ??Z????ZZ???ZZ?ZZ????ZZ???ZZZ?",
 "????ZZ?ZZ?ZZ?ZZ??ZZZ???ZZZ??Z???Z??ZZ?Z?????Z????Z",
 "??ZZ?Z??Z?ZZ???ZZ?Z?Z?Z?????Z?Z???Z??ZZ??Z?Z?ZZ??Z", 
 "?ZZZZ??Z?Z?ZZZ?Z?Z?Z?ZZZ???Z??Z?ZZ??Z?Z??Z??Z?Z??Z",
 "ZZ?Z???Z??ZZZ?ZZZ?ZZ?ZZ?ZZ???ZZZZ?Z??Z?Z?Z?Z??Z??Z"}
Returns: 
{"AAHAAAAABAEEAAGCBAHEAGACACAAAABAAAAJGAAGDAAAAFAEEE",
"ADHNIAAJKAHENAKCBAHKMGLCGEANAAGAKALJGMAHMAACPFEENJ",
"AKOVLAAJKAKENTKPBAHLMGNCNEAOAAGAMILYGQKHNRAEPRFENJ",
"AMOZLANJTAKRNTKPBAHLTPNOQEASYAGZMOLZGYTLNRMGPRFYVJ",
"WMOZLANJZATXNZKPBXZMYRNXQELSYQGZMOLZGYTLNTMJPRFYZJ",
"ZYZZLANJZSTZZZKZBXZVYYNXQELZYRGZZVZZGZTLZTMMPVFZZJ",
"ZYZZLZNXZSUZZZZZBZZYYZVXZEMZYWGZZVZZZZTLZTMTZVFZZZ",
"ZYZZLZNXZSUZZZZZZZZZYZVXZEMZYZGZZZZZZZTZZTMTZVFZZZ",
"ZYZZLZNXZZUZZZZZZZZZZZVZZZMZYZZZZZZZZZZZZZMTZZFZZZ",
"ZYZZLZZXZZVZZZZZZZZZZZVZZZSZYZZZZZZZZZZZZZMTZZWZZZ",
"ZYZZLZZZZZVZZZZZZZZZZZVZZZSZYZZZZZZZZZZZZZZTZZWZZZ",
"ZYZZLZZZZZVZZZZZZZZZZZVZZZSZZZZZZZZZZZZZZZZTZZZZZZ",
"ZYZZLZZZZZVZZZZZZZZZZZVZZZSZZZZZZZZZZZZZZZZTZZZZZZ",
"ZYZZLZZZZZVZZZZZZZZZZZVZZZZZZZZZZZZZZZZZZZZTZZZZZZ",
"ZYZZZZZZZZVZZZZZZZZZZZVZZZZZZZZZZZZZZZZZZZZTZZZZZZ",
"ZYZZZZZZZZVZZZZZZZZZZZVZZZZZZZZZZZZZZZZZZZZTZZZZZZ",
"ZYZZZZZZZZVZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZTZZZZZZ",
"ZYZZZZZZZZVZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZTZZZZZZ",
"ZYZZZZZZZZVZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZTZZZZZZ",
"ZZZZZZZZZZVZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZTZZZZZZ",
"ZZZZZZZZZZVZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZTZZZZZZ",
"ZZZZZZZZZZVZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZTZZZZZZ",
"ZZZZZZZZZZVZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZTZZZZZZ",
"ZZZZZZZZZZVZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZTZZZZZZ",
"ZZZZZZZZZZWZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZWZZZZZZ",
"ZZZZZZZZZZWZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZWZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZWZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZWZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZWZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZWZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZWZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ" }
5)
    
{"BI", "AQ"}
Returns: { }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

IdealString

Greedy, Simple Math, String Manipulation



Used in:

SRM 405

Used as:

Division II Level Three

Writer:

Petr

Testers:

PabloGilberto , Olexiy , Jan_Kuipers , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9757

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12177&pm=9757

Problem Statement

    

An ideal string is a string where the 1-based index of the first occurrence of each letter is equal to the number of occurrences of that letter in the string. For example, the "BAOOOA" is an ideal string (quotes for clarity only). The letter 'B' appears 1 time, and its index is 1. The letter 'A' occurs 2 times and its first index is 2. The letter 'O' occurs 3 times and its first index is 3.

Given an int length, return the lexicographically smallest ideal string of that length containing only uppercase letters ('A'-'Z'). If there are no such ideal strings of that length, return an empty String instead.

 

Definition

    
Class:IdealString
Method:construct
Parameters:int
Returns:String
Method signature:String construct(int length)
(be sure your method is public)
    
 

Notes

-String A is lexicographically smaller than string B of the same length if it contains a smaller letter at the first position they differ. Letter X is smaller than letter Y if it comes earlier in the alphabet.
 

Constraints

-length will be between 1 and 100, inclusive.
 

Examples

0)
    
1
Returns: "A"
1)
    
3
Returns: "ABB"
2)
    
2
Returns: ""
There's no way we can construct an ideal string of length 2 - if both its characters are equal, then the number of occurrences (2) and the position of its first occurrence (1) do not match; if they are distinct, then for the second character the number of occurrences (1) and the position of its first occurrence (2) do not match as well.
3)
    
6
Returns: "ABCBCC"
We can permute the last 3 characters in any way, but this way gets us the lexicographically smallest answer.
4)
    
7
Returns: "ABBCCCC"
5)
    
5
Returns: ""

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WorkersOnPlane

Graph Theory, Search, String Parsing



Used in:

SRM 422

Used as:

Division I Level Three

Writer:

mateuszek

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9751

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13513&pm=9751

Problem Statement

    You have recently bought a field containing gold and silver, and you want to hire some workers to gather the treasure and build beautiful things with it. The field is divided into square cells of equal size. You are given a String[] field, where the j-th character of the i-th element is the content of the cell at row i, column j. A period ('.') represents grass, an uppercase 'X' represents rocks, and uppercase 'G' and 'S' represent gold and silver, respectively. You have also built special workplace cells for your workers, each denoted by an uppercase 'W'.



Each worker must be assigned exactly one workplace, one gold cell and one silver cell. None of these three cells can be assigned to any of the other workers. Each worker will be transporting gold and silver from his cells to his workspace, and for efficiency reasons, you do not want workers to carry anything for more than K meters. This means every worker's workplace must be at most K meters away from his gold cell and at most K meters away from his silver cell. Distance is measured as follows. From each cell, a worker can only move left, right, up or down to an adjacent cell (if one exists). The distance between two consecutive cells is one meter. Workers are only allowed to walk on grass when moving between their cells.



Return the largest number of workers you can hire while meeting these requirements.
 

Definition

    
Class:WorkersOnPlane
Method:howMany
Parameters:String[], int
Returns:int
Method signature:int howMany(String[] field, int K)
(be sure your method is public)
    
 

Constraints

-field will contain between 1 and 30 elements, inclusive.
-Each element of field will contain between 1 and 30 characters, inclusive.
-Each element of field will contain the same number of characters.
-Each character in each element of field will be a period ('.'), an uppercase 'X', an uppercase 'G', an uppercase 'S' or an uppercase 'W'.
-K will be between 1 and 1000, inclusive.
 

Examples

0)
    
{ "G..X",
  "..XS",
  "W..." }
5
Returns: 1
1)
    
{ "GG..",
  "....",
  "..W.",
  "..W.",
  "SS.." }
4
Returns: 2
2)
    
{ "GG..",
  "XX..",
  "..W.",
  "..W.",
  "SS.." }
10
Returns: 1
We can hire only one worker, because the gold mine in the top left corner can't be reached from any of the workplaces.
3)
    
{"G.XXX.S",
 "G..WW.S"}
11
Returns: 0
If we hire a worker for the left workplace, he won't be able to reach any of the silver mines. Similarly, if we hire a worker for the right workplace, he won't be able to reach gold mines. So we can't hire anybody.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

NumberPartition

Dynamic Programming, Math, Search



Used in:

TCHS SRM 54

Used as:

Division I Level Three

Writer:

mateuszek

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9750

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13523&pm=9750

Problem Statement

    A partition of the number n is the set of numbers that all sum up to n. For example, we have 5 different partitions of 4: {1, 1, 1, 1}, {1, 1, 2}, {1, 3}, {2, 2}, {4}. If we sort all the numbers within each set, we can treat each partition as a sorted list of numbers and so introduce a lexicographic order on all partitions. For example, the partitions of 4 mentioned before are given in order. You are given ints n and k. Determine all the partitions of n, sort them in lexicographical order, and return a int[] containing the k-th one (k is a 1-based index). If there are not enough partitions of n, return an empty int[].
 

Definition

    
Class:NumberPartition
Method:kthPartition
Parameters:int, int
Returns:int[]
Method signature:int[] kthPartition(int n, int k)
(be sure your method is public)
    
 

Notes

-The lexicographical order is exactly the same as in a dictionary. A int[] A is lexicographically before a int[] B if there exists an integer i such that A[i] < B[i] and A[j] = B[j] for all j < i or if A is a proper prefix of B.
 

Constraints

-n will be between 1 and 50, inclusive.
-k will be between 1 and 1000000, inclusive.
 

Examples

0)
    
4
1
Returns: {1, 1, 1, 1 }
Example from the problem statement.
1)
    
4
3
Returns: {1, 3 }
2)
    
17
123
Returns: {1, 1, 1, 3, 3, 3, 5 }
3)
    
12
1234
Returns: { }
There are less then 1234 partitions of 12.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ClosestRegex

Dynamic Programming, String Manipulation



Used in:

SRM 410

Used as:

Division II Level Three

Writer:

bmerry

Testers:

PabloGilberto , legakis , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9727

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12182&pm=9727

Problem Statement

    

A regular expression is a pattern describing how a particular string should be formed. For the purposes of this problem, a regular expression consists of atoms. Each atom is either a single lowercase letter (which matches exactly one of that letter), or a single lowercase letter followed by an asterisk ('*'), which matches zero or more of that letter. A string matches a regular expression if it can be partitioned into substrings which match the atoms of the regular expression in the same order. For example, the regular expression ab*c*b is matched by the strings ab, abb, acb and abbbcccb, but not by ba, accbb or babcb.

You have a string text which ought to match the regular expression regex. However, it may have been corrupted. Return the string S that satisfies the following conditions.

  1. S has the same number of characters as text.
  2. S matches regex.
  3. The number of positions in which S differs from text is minimal.
  4. S is lexicographically smallest amongst strings that satisfy the other conditions.

If there is no string that satisfies the above conditions, return the empty string.

 

Definition

    
Class:ClosestRegex
Method:closestString
Parameters:String, String
Returns:String
Method signature:String closestString(String text, String regex)
(be sure your method is public)
    
 

Constraints

-text will contain between 1 and 50 characters, inclusive.
-text will contain only lowercase letters ('a' - 'z').
-regex will contain between 1 and 50 characters, inclusive.
-regex will contain only lowercase letters and '*'s.
-The first character of regex will not be a '*'.
-regex will not contain two consecutive '*'s.
 

Examples

0)
    
"abcd"
"bcdd"
Returns: "bcdd"
Here there are no asterisks, so only one string can match. 'a' must be changed to 'b', 'b' to 'c' and 'c' to 'd'.
1)
    
"topcoder"
"t*px*coa*de*"
Returns: "ttpcodee"
Changing the string to ttpcodee requires two changes.
2)
    
"cmu"
"c*m*fm*u*"
Returns: "cfu"
Any of fmu, cfu and cmf would require one change, but cfu is first lexicographically.
3)
    
"aaaaacccc"
"a*abc*"
Returns: "aaaaabccc"
4)
    
"short"
"lo*ts*of*let*ter*s"
Returns: ""
No 5-letter string matches the regex.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RoadReform

Graph Theory



Used in:

East China Round 2

Used as:

Division I Level Three

Writer:

Mike Mirzayanov

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9721

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12227&pm=9721

Problem Statement

    

There are n cities in the Kingdom. Some pairs of cities are connected by bidirectional roads, and there exists a path between every pair of cities.

The King thinks that supporting so many roads is very expensive, so he decided to close some of them. He wants to close as many roads as possible, but, of course, he still wants each city to be reachable from any other city.

A city is a dead end if it is connected to only one other city by a direct road. You will be given a String[] roads, with the j-th character of the i-th element of roads being '1' (one) if the i-th and j-th cities are connected by a direct road, and '0' (zero) otherwise. Return the maximal number of dead ends the Kingdom may have after the reform.

 

Definition

    
Class:RoadReform
Method:findMaxDeadendCount
Parameters:String[]
Returns:int
Method signature:int findMaxDeadendCount(String[] roads)
(be sure your method is public)
    
 

Constraints

-roads will contain between 2 and 15 elements, inclusive.
-Each element of roads will contain exactly n characters, where n is the number of elements in roads.
-Each element of roads will contain digits '0' and '1' only.
-The j-th character in the i-th element of roads will be equal to the i-th character in the j-th element.
-The i-th character in the i-th element of roads will be '0'.
-Each pair of cities in the input will be connected by a path.
 

Examples

0)
    
{"01",
 "10"}
Returns: 2
Two cities are connected by a road. The King can't close this road and both cities will still be dead ends.
1)
    
{"01000", 
 "10100",
 "01010",
 "00101",
 "00010"}
Returns: 2
The cities of the Kingdom are aligned in a chain. As in example 0, no road can be closed without splitting the Kingdom.
2)
    
{"01111",
 "10000",
 "10000",
 "10000",
 "10000"}
Returns: 4
3)
    
{"0111",
 "1011",
 "1101",
 "1110"}
Returns: 3
Each pair of cities is connected by a direct road. The King can close roads 1<->2, 2<->3 and 1<->3, thus making cities 1, 2 and 3 dead ends.
4)
    
{"0100000001",
 "1010000000",
 "0101000000",
 "0010100000",
 "0001010000",
 "0000101000",
 "0000010100",
 "0000001010",
 "0000000101",
 "1000000010"}
Returns: 2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WhackAMole

Brute Force, Simple Search, Iteration



Used in:

TCO08 Semifinal 3

Used as:

Division I Level One

Writer:

SnapDragon

Testers:

PabloGilberto , lbackstrom , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8819

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12017&pm=8819

Problem Statement

    You are designing a new Whack-A-Mole game for the local carnival. However, you have a mean streak, and you'd like to make the game impossible to win.



The game consists of a certain number of holes arranged in a circle. There are also a certain number of hammers attached to it. Several players can play the game at once. They each take one hammer, choose a hole, and then guard it. If a mole ever pops out of that hole, they will WHACK it!



The inner workings of the game are as follows. There is a circular plate underneath the holes with several electronic "moles" attached to it, in some fixed configuration. After the players are positioned, the game software will sense which holes are guarded. It can then rotate the plate however it wants. Finally, the moles will pop out of the holes they're currently under. The software will do its best to position the moles to prevent any moles from getting WHACKed!



Figure out a configuration of moles that allows you to prevent the players from WHACKing any moles, no matter how they position themselves. A configuration may be represented as a String with an uppercase 'X' where the moles are positioned and an uppercase letter 'O' elsewhere. (Of course, since the moles are on a circular plate, a given configuration has multiple String representations.) Choose a configuration with the most moles; among these, return the lexicographically smallest String representation.
 

Definition

    
Class:WhackAMole
Method:placeMoles
Parameters:int, int
Returns:String
Method signature:String placeMoles(int numHoles, int numHammers)
(be sure your method is public)
    
 

Notes

-String A is smaller than String B if A has a smaller character at the first position where the strings differ.
 

Constraints

-numHoles will be between 1 and 10, inclusive.
-numHammers will be between 1 and numHoles, inclusive.
 

Examples

0)
    
1
1
Returns: "O"
The only hole is guarded - a very unfriendly environment for moles!
1)
    
4
2
Returns: "OOOX"
The correct arrangement of players will defeat both "OOXX" and "OXOX".
2)
    
5
2
Returns: "OOOXX"
Every possible arrangement of players will still leave a pair of consecutive holes unguarded.
3)
    
6
2
Returns: "OOXOXX"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AddElectricalWires

Brute Force, Graph Theory, Recursion



Used in:

SRM 410

Used as:

Division I Level One , Division II Level Two

Writer:

SnapDragon

Testers:

PabloGilberto , lbackstrom , bmerry , legakis , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8817

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12182&pm=8817

Problem Statement

    You are given an electrical circuit for a home, with a number of nodes possibly connected by wires. Any pair of nodes may be connected by at most one wire, and a node can't be connected to itself. Each node on the circuit is either an electrical outlet for the house or a connection to the main electrical grid. The String[] wires tells you the wires that are already in place; the xth character of the yth element is '1' (one) if nodes x and y have a wire between them, '0' (zero) otherwise. The int[] gridConnections lists the indices of the nodes that are connections to the main electrical grid.



You'd like to make the circuit safer and more redundant by adding as many extra wires to it as possible. The one complication is that no two main grid connections are currently wired together (directly or indirectly), and you must preserve this, or else disaster will result. Determine the maximum number of new wires you can add to the circuit.
 

Definition

    
Class:AddElectricalWires
Method:maxNewWires
Parameters:String[], int[]
Returns:int
Method signature:int maxNewWires(String[] wires, int[] gridConnections)
(be sure your method is public)
    
 

Constraints

-wires will contain between 1 and 50 elements, inclusive.
-Each element of wires will have the same length as wires.
-Each element of wires will contain only the characters '0' and '1'.
-Character i of element i of wires will be a '0'.
-Character i of element j of wires will be the same as character j of element i.
-gridConnections will contain between 1 and 50 elements, inclusive.
-Each element of gridConnections will be an integer between 0 and length(wires)-1, inclusive.
-Each element of gridConnections will be distinct.
-Each pair of elements of gridConnections will not index nodes connected by a path of '1's in wires.
 

Examples

0)
    
{"000","000","000"}
{0}
Returns: 3
Every valid wire can be added.
1)
    
{"000","000","000"}
{0,1}
Returns: 1
0 and 1 can't be connected, but 0 and 2 (or 1 and 2) still can be.
2)
    
{"01","10"}
{0}
Returns: 0
This circuit is already complete.
3)
    
{"00000","00000","00000","00000","00000"}
{0,1,2,3,4}
Returns: 0
Any connections would be disastrous.
4)
    
{"01000","10100","01010","00100","00000"}
{2,4}
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ShortPaths

Dynamic Programming, Graph Theory, Math, Search



Used in:

SRM 406

Used as:

Division I Level Three

Writer:

eleusive

Testers:

PabloGilberto , Olexiy , gawry , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8791

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12178&pm=8791

Problem Statement

    You're given a weighted, directed graph that satisfies two conditions: each vertex is contained in at most one simple cycle, and for any two vertices u and v, there exists at most one simple path from u to v (see the notes section for definitions).



The graph is described by a String[] graph, where the jth character of the ith element of graph is either '0' if there is no edge from vertex i to j, or a digit between '1' and '9', inclusive, which is the weight of the edge from vertex i to j.



Given such a graph, return the length of the kth shortest path from start to finish. If there are fewer than k paths, you should return -1. Note that all paths of the same length should be counted (see example 3 for clarification).
 

Definition

    
Class:ShortPaths
Method:getPath
Parameters:String[], long, int, int
Returns:long
Method signature:long getPath(String[] graph, long k, int start, int finish)
(be sure your method is public)
    
 

Notes

-A simple path is an ordered sequence of distinct vertices such that for each vertex in the sequence, there is an edge to the next vertex in the sequence (except for the last vertex).
-A simple cycle is an ordered sequence of vertices such that for each vertex in the sequence, there is an edge to the next vertex in the sequence (except the last vertex). In addition, the sequence must contain no repeated vertices, except for the first and last vertices which must be the same.
 

Constraints

-k will be between 1 and 10^12, inclusive.
-The graph represented by graph will satisfy the constraints described in the problem statement.
-graph will contain between 2 and 50 elements, inclusive.
-Each element of graph will contain exactly N characters, where N is the number of elements in graph.
-Each character in graph will be a digit between '0' and '9', inclusive.
-The ith character of the ith element of graph will always be '0'.
-start and finish will be distinct integers between 0 and N-1, inclusive, where N is the number of elements in graph.
 

Examples

0)
    
{
"0100",
"0020",
"0003",
"4000"
}
1
0
2
Returns: 3
The direct path between nodes 0 and 2 is 0->1->2.
1)
    
{
"0100",
"0020",
"0003",
"4000"
}
2
0
2
Returns: 13
The same graph as above, but the second shortest path is 0->1->2->3->0->1->2.
2)
    
{
"011",
"000",
"000"
}
1
1
2
Returns: -1
There is no path from vertex 1 to vertex 2.
3)
    
{
"010000",
"001010",
"000101",
"000000",
"010000",
"001000"
}
3
0
3
Returns: 5
The shortest path is of length 3. The next two shortest paths are both of length 5, and since all paths of length 5 must be counted, the third shortest path is of length 5.
4)
    
{
"010000",
"001010",
"000103",
"000000",
"010000",
"002000"
}
11
0
3
Returns: 14
5)
    
{
"010000000",
"001002000",
"000100000",
"000010900",
"000000006",
"030000000",
"007000000",
"000040000",
"000000070"
}
5621
0
7
Returns: 363
6)
    
{
"09000000000000000000000002000000000000000000000000",
"00900000000000000000000000000000000000000000000000",
"00090000000000000000000000000000000000000000000000",
"00009000000000000000000000000000000000000000000000",
"00000900000000000000000000000000000000000000000000",
"00000090000000000000000000000000000000000000000000",
"00000009000000000000000000000000000000000000000000",
"00000000900000000000000000000000000000000000000000",
"00000000090000000000000000000000000000000000000000",
"00000000009000000000000000000000000000000000000000",
"00000000000900000000000000000000000000000000000000",
"00000000000090000000000000000000000000000000000000",
"00000000000009000000000000000000000000000000000000",
"00000000000000900000000000000000000000000000000000",
"00000000000000090000000000000000000000000000000000",
"00000000000000009000000000000000000000000000000000",
"00000000000000000900000000000000000000000000000000",
"00000000000000000090000000000000000000000000000000",
"00000000000000000009000000000000000000000000000000",
"00000000000000000000900000000000000000000000000000",
"00000000000000000000090000000000000000000000000000",
"00000000000000000000009000000000000000000000000000",
"00000000000000000000000900000000000000000000000000",
"00000000000000000000000090000000000000000000000000",
"40000000000000000000000000000000000000000000000000",
"00000000000000000000000000900000000000000000000000",
"00000000000000000000000000090000000000000000000000",
"00000000000000000000000000009000000000000000000000",
"00000000000000000000000000000900000000000000000000",
"00000000000000000000000000000090000000000000000000",
"00000000000000000000000000000009000000000000000000",
"00000000000000000000000000000000900000000000000000",
"00000000000000000000000000000000090000000000000000",
"00000000000000000000000000000000009000000000000000",
"00000000000000000000000000000000000900000000000000",
"00000000000000000000000000000000000090000000000000",
"00000000000000000000000000000000000009000000000000",
"00000000000000000000000000000000000000900000000000",
"00000000000000000000000000000000000000090000000000",
"00000000000000000000000000000000000000009000000000",
"00000000000000000000000000000000000000000900000000",
"00000000000000000000000000000000000000000090000000",
"00000000000000000000000000000000000000000009000000",
"00000000000000000000000000000000000000000000900000",
"00000000000000000000000000000000000000000000090000",
"00000000000000000000000000000000000000000000009000",
"00000000000000000000000000000000000000000000000900",
"00000000000000000000000000000000000000000000000090",
"00000000000000000000000000000000000000000000000009",
"00000000000000000000000004000000000000000000000000"
}
10000000000
0
49
Returns: 31112618

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BinaryMatrix

Search



Used in:

TCO08 Semifinal 1

Used as:

Division I Level Three

Writer:

Mike Mirzayanov

Testers:

PabloGilberto , SnapDragon , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8781

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12015&pm=8781

Problem Statement

    

You are given a binary rectangular matrix with exactly five columns. A matrix is called good if it contains exactly columns[i] ones in the i-th column. To make the matrix good, you are allowed to perform at most maxMoveCount moves. With each move, you select a row of the matrix and circularly shift it to the right by 1 position (so, for example, row {0, 0, 1, 0, 0} becomes {0, 0, 0, 1, 0}).

Given matrix, columns and maxMoveCount, return the lexicographically greatest good matrix you can achieve. If you can not achieve any good matrix, return an empty String[]. To compare two matrices lexicographically, concatenate all rows starting from the top for each of the matrices and compare the resulting strings. String A is lexicographically greater than string B if it contains the bigger character at the first position where they differ.

 

Definition

    
Class:BinaryMatrix
Method:getMaximalLexicographically
Parameters:String[], int[], int
Returns:String[]
Method signature:String[] getMaximalLexicographically(String[] matrix, int[] columns, int maxMoveCount)
(be sure your method is public)
    
 

Constraints

-matrix will contain between 1 and 40 elements, inclusive.
-Each element of matrix will contain exactly five digits.
-Each element of matrix will contain only digits '0' or '1'.
-columns will contain exactly five elements.
-Each element of columns will be between 0 and 40, inclusive.
-maxMoveCount will be between 0 and 160, inclusive.
 

Examples

0)
    
{"01000", "10000"}
{1,1,0,0,0}
5
Returns: {"10000", "01000" }
Shift the first row 4 times and the second row once.
1)
    
{"01000", "10000"}
{1,1,0,0,0}
4
Returns: {"01000", "10000" }
Don't change anything.
2)
    
{"00100", "10000", "00010", "00001", "01000"}
{1,1,1,1,1}
7
Returns: {"10000", "01000", "00010", "00001", "00100" }
3)
    
{"00011","00010","11000"}
{0,1,2,2,0}
9
Returns: {"01100", "00010", "00110" }
4)
    
{"00000","11111"}
{5,0,0,0,0}
160
Returns: { }
5)
    
{"00011"}
{0,1,0,1,0}
160
Returns: { }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

StringInterspersal

Greedy, String Manipulation



Used in:

SRM 414

Used as:

Division I Level Two

Writer:

StevieT

Testers:

PabloGilberto , Olexiy , gawry , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8772

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13505&pm=8772

Problem Statement

    

A String S is an interspersal of a set of Strings W, if W is a set of disjoint subsequences of S which cover S. Less formally, S can be formed from W by partitioning each member of W into substrings, then concatenating all the substrings, while maintaining the order of the substrings within each element of W. For example, if W contains the strings {"DESIGN", "ALGORITHM", "MARATHON"}, then one possible interspersal would be "ADELGMAORARISIGNTHMTHON", formed as shown below.



 DE         SIGN

A  LG  O  RI    THM

     MA RA         THON

-----------------------

ADELGMAORARISIGNTHMTHON


Given a String[] W, return the lexicographically minimum interspersal of the Strings in W

 

Definition

    
Class:StringInterspersal
Method:minimum
Parameters:String[]
Returns:String
Method signature:String minimum(String[] W)
(be sure your method is public)
    
 

Notes

-The lexicographically minimum of two Strings is the one with the alphabetically earlier character at the first position at which they differ.
-The return String will contain no more than 1000 characters.
 

Constraints

-W will contain between 1 and 20 elements, inclusive.
-Each element of W will contain between 1 and 50 uppercase letters ('A'-'Z'), inclusive.
 

Examples

0)
    
{"DESIGN","ALGORITHM","MARATHON"}
Returns: "ADELGMAORARISIGNTHMTHON"
The example from the problem statement.
1)
    
{"TOMEK","PETR","ACRUSH","BURUNDUK","KRIJGERTJE"}
Returns: "ABCKPERIJGERRTJETOMEKTRURUNDUKUSH"
2)
    
{"CCCA","CCCB","CCCD","CCCE"}
Returns: "CCCACCCBCCCCCCDE"
3)
    
{"BKSDSOPTDD","DDODEVNKL","XX","PODEEE","LQQWRT"}
Returns: "BDDKLODEPODEEEQQSDSOPTDDVNKLWRTXX"
4)
    
{"TOPCODER","BETFAIR","NSA","BT","LILLY"}
Returns: "BBELILLNSATFAIRTOPCODERTY"
5)
    
{"QITHSQARQV","BYLHVGMLRY","LKMAQTJEAM","AQYICVNIKK","HKGZZFFEWC"}
Returns: "ABHKGLKMAQIQQTHSQARQTJEAMVYICVNIKKYLHVGMLRYZZFFEWC"
6)
    
{"XHCYBTUQUW","EKBISADSSN","LOOISPOFAK","MIXBDHPJUQ","BNMNDHMOTC"}
Returns: "BEKBILMINMNDHMOOIOSADSPOFAKSSNTCXBDHPJUQXHCYBTUQUW"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FairDiceGame

Greedy, Simple Math



Used in:

TCO08 Semifinal 2

Used as:

Division I Level One

Writer:

misof

Testers:

PabloGilberto , legakis , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8769

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12016&pm=8769

Problem Statement

    

Several people play with a 6-sided die and take alternating turns. In each turn the player starts by throwing the die, and the player who throws a '6' wins immediately. Obviously, each turn entails a one in six chance of winning. As soon as one player wins, the game ends and all other players lose the game.

The game is not fair. For example, in a two-player version, the first player is expected to win 6 out of 11 games.

In our problem playerCount mathematicians decided to play a fair version of the game. After a while, they came up with a solution -- they will not take alternating turns. Instead, they will find and follow a different sequence of turns that will make the game fair. (See notes for a precise definition.)

For simplicity, assume that the players are assigned the first playerCount letters of the alphabet. Then the sequence of turns can be represented as an infinite string of letters. Out of all fair sequences we will be interested in the lexicographically smallest one.

You are given an int playerCount, and an int turnNumber. Your method should find the lexicographically smallest fair sequence of moves for playerCount players, and return a one-character String containing the player that has to play in the turn turnNumber. Turns are numbered starting from 1. If there is no fair sequence of moves for playerCount players, return an empty string instead.

 

Definition

    
Class:FairDiceGame
Method:getPlayer
Parameters:int, int
Returns:String
Method signature:String getPlayer(int playerCount, int turnNumber)
(be sure your method is public)
    
 

Notes

-Given two different sequences of turns X and Y, sequence X is lexicographically smaller than Y if and only if at the first place where they differ the character in X is earlier in the alphabet than the one in Y.
-An infinite sequence of turns S is fair if for any player P and for any number of turns T the following sentence is true: If the players take turns according to the sequence, then the probability that player P wins in one of the first T turns is at most equal to 1/playerCount.
 

Constraints

-playerCount will be between 2 and 26, inclusive.
-turnNumber will be between 1 and 20, inclusive.
 

Examples

0)
    
2
1
Returns: "A"
For two players, there are many fair sequences of turns. In the lexicographically smallest one, the first player must obviously be A.
1)
    
2
2
Returns: "A"
There is at least one fair sequence such that A takes the second turn as well.
2)
    
2
4
Returns: "B"
In the lexicographically smallest fair sequence for two players the player A takes the first three turns, and B takes the fourth one.
3)
    
17
20
Returns: ""
There is no fair sequence of turns for 17 players.
4)
    
3
4
Returns: "B"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

HouseProtection

Geometry, Graph Theory, Search, Simple Math



Used in:

SRM 397

Used as:

Division I Level Three

Writer:

mateuszek

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8762

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12169&pm=8762

Problem Statement

    

You have recently started to feel unsafe in your own house, so you decided to place surveillance radars in the garden. When a radar with range r is placed at point S, it totally covers the area of the circle with radius r centered at point S. The maximum allowable range is R, and all your radars must be set to the same range.



There are two types of radars - blue and red. You can buy as many of each as you like, but they can only be placed at certain points in the garden. You are given two int[]s possibleXForBlue and possibleYForBlue, where (possibleXForBlue[i], possibleYForBlue[i]) is the i-th point where you are allowed to place a blue radar. Similarly, you are given two int[]s possibleXForRed and possibleYForRed describing the allowable points for red radars. You cannot place more than one radar at a single point. Also, the area covered by blue radars cannot overlap with the area covered by red radars. Otherwise, the whole system will malfunction.



Your goal is to place the radars in such a way that maximizes the safety factor. The safety factor is the sum of all the areas covered by the radars. Note that if an area is covered by multiple radars, it will count multiple times toward the sum. Return the maximal safety factor you can achieve.

 

Definition

    
Class:HouseProtection
Method:safetyFactor
Parameters:int[], int[], int[], int[], int
Returns:double
Method signature:double safetyFactor(int[] possibleXForBlue, int[] possibleYForBlue, int[] possibleXForRed, int[] possibleYForRed, int R)
(be sure your method is public)
    
 

Notes

-The returned value must be accurate to within a relative or absolute value of 1E-9.
 

Constraints

-possibleXForBlue will contain between 1 and 50 elements, inclusive.
-possibleXForBlue and possibleYForBlue will both contain the same number of elements.
-Each element of possibleXForBlue will be between -1000 and 1000, inclusive.
-Each element of possibleYForBlue will be between -1000 and 1000, inclusive.
-All points represented by possibleXForBlue and possibleYForBlue will be distinct.
-possibleXForRed will contain between 1 and 50 elements, inclusive.
-possibleXForRed and possibleYForRed will both contain the same number of elements.
-Each element of possibleXForRed will be between -1000 and 1000, inclusive.
-Each element of possibleYForRed will be between -1000 and 1000, inclusive.
-All points represented by possibleXForRed and possibleYForRed will be distinct.
-R will be between 1 and 1000, inclusive.
 

Examples

0)
    
{ 0, 4 }
{ 0, 0 }
{ 2, 1 }
{ 2, -1 }
1
Returns: 9.42477796076938
We can place two blue radars at points (0,0) and (4,0) and one red radar at point (2,2). Setting their ranges to 1 will give us the safety factor of about 3.14 * 3 = 9.42.
1)
    
{ 1 }
{ 1 }
{ 1 }
{ 1 }
5
Returns: 78.53981633974483
Note that there may be overlap between the allowable points for blue radars and the allowable points for red radars.
2)
    
{ 0 }
{ 0 }
{ 100 }
{ 0 }
51
Returns: 15707.963267948966
3)
    
{ 23, 29, 29, 35 }
{ 77, 79, 75, 77 }
{ 26, 26, 32 }
{ 78, 76, 76 }
3
Returns: 113.09733552923255

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DancingParty

Graph Theory



Used in:

SRM 399

Used as:

Division I Level Three

Writer:

andrewzta

Testers:

PabloGilberto , Olexiy , marek.cygan , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8754

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12171&pm=8754

Problem Statement

    

You are organizing a dance party. The party will be attended by n boys and n girls. There will be several rounds of dancing.

In each round, you divide the guests into n dancing pairs. Each guest must be in exactly one pair, and each pair must contain one boy and one girl. Each boy must dance with a different girl in every round. Some boys and girls like each other and some do not. During the party, each boy agrees to dance with at most k girls he doesn't like. Similarly, each girl agrees to dance with at most k boys she doesn't like.

You are given a String[] likes. The j-th character of likes[i] is 'Y' if the i-th boy and the j-th girl like each other, and 'N' if they don't. Return the maximum number of rounds you can organize.

 

Definition

    
Class:DancingParty
Method:maxDances
Parameters:String[], int
Returns:int
Method signature:int maxDances(String[] likes, int k)
(be sure your method is public)
    
 

Constraints

-likes will contain between 1 and 50 elements, inclusive.
-Each element of likes will contain exactly n characters, where n is the number of elements in likes.
-Each element of likes will contain only the characters 'Y' and 'N'.
-k will be between 0 and 50, inclusive.
 

Examples

0)
    
{"YYY", "YYY", "YYY"}
0
Returns: 3
Every boy likes every girl, so you can organize 3 rounds.
1)
    
{"YYY", "YYN", "YNY"}
0
Returns: 2
For example, you can have one round with pairs 1-2, 2-1 and 3-3 and one round with pairs 1-3, 2-2 and 3-1.
2)
    
{"YN", "YN"}
0
Returns: 0
The second girl doesn't like anybody.
3)
    
{"YN", "YN"}
1
Returns: 1
The second girl doesn't like anybody again, but this time she agrees to dance with someone she doesn't like once.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SortingGame

Graph Theory, Simple Search, Iteration, Sorting



Used in:

SRM 397

Used as:

Division I Level One , Division II Level Two

Writer:

mateuszek

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8745

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12169&pm=8745

Problem Statement

    In The Sorting Game, you are given a sequence containing a permutation of the integers between 1 and n, inclusive. In one move, you can take any k consecutive elements of the sequence and reverse their order. The goal of the game is to sort the sequence in ascending order. You are given a int[] board describing the initial sequence. Return the fewest number of moves necessary to finish the game successfully, or -1 if it's impossible.
 

Definition

    
Class:SortingGame
Method:fewestMoves
Parameters:int[], int
Returns:int
Method signature:int fewestMoves(int[] board, int k)
(be sure your method is public)
    
 

Constraints

-board will contain between 2 and 8 elements, inclusive.
-Each integer between 1 and the size of board, inclusive, will appear in board exactly once.
-k will be between 2 and the size of board, inclusive.
 

Examples

0)
    
{1,2,3}
3
Returns: 0
The sequence is already sorted, so we don't need any moves.
1)
    
{3,2,1}
3
Returns: 1
We can reverse the whole sequence with one move here.
2)
    
{5,4,3,2,1}
2
Returns: 10
This one is more complex.
3)
    
{3,2,4,1,5}
4
Returns: -1
4)
    
{7,2,1,6,8,4,3,5}
4
Returns: 7

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

IngredientProportions

Graph Theory, Simple Math, String Parsing



Used in:

SRM 429

Used as:

Division I Level Two , Division II Level Three

Writer:

darnley

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8729

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13520&pm=8729

Problem Statement

    

Your friend has invented a splendid cocktail consisting of N ingredients. However, she has forgotten the amount of each ingredient that goes into the recipe.

For N-1 pairs of ingredients, she remembers the proportion in which the ingredients within each pair should be added to the cocktail. Fortunately, these N-1 proportions are sufficient to restore the recipe of the entire cocktail.

You are given a String[] proportions containing the N-1 proportions. Each element is formatted "#<a> and #<b> as <p>:<q>" (quotes for clarity), which means that the mass of ingredient <a> divided by the mass of ingredient <b> in the cocktail must be equal to <p>/<q> (all ingredients are 0-indexed). Return a int[] containing exactly N elements, where the i-th element is the mass of ingredient i, such that all the given proportions are satisfied and the total mass is as small as possible. The total mass must be greater than 0.

 

Definition

    
Class:IngredientProportions
Method:getMasses
Parameters:String[]
Returns:int[]
Method signature:int[] getMasses(String[] proportions)
(be sure your method is public)
    
 

Constraints

-proportions will contain between 1 and 9 elements, inclusive.
-proportions will contain exactly N-1 elements, where N is the number of ingredients in the cocktail.
-Each element of proportions will contain exactly 16 characters.
-Each element of proportions will be formatted as described in the statement.
-Each <a> will be between 0 and N-1, inclusive.
-Each <b> will be between 0 and N-1, inclusive.
-Each <p> will be between 1 and 9, inclusive.
-Each <q> will be between 1 and 9, inclusive.
-The information given in proportions will be sufficient to restore the recipe of the cocktail uniquely up to a constant factor.
 

Examples

0)
    
{"#0 and #1 as 6:4"}
Returns: {3, 2 }
Taking 6 units of ingredient #0 and 4 units of ingredient #1 would satisfy the proportion, but it wouldn't give the smallest possible total mass. To minimize the total mass, divide the masses by 2.
1)
    
{"#0 and #1 as 9:8","#1 and #2 as 9:8"}
Returns: {81, 72, 64 }
2)
    
{"#4 and #0 as 1:1", "#4 and #1 as 3:1", "#4 and #2 as 5:1", "#4 and #3 as 7:1"}
Returns: {105, 35, 21, 15, 105 }
The mass of ingredient #4 should be divisible by 3, 5 and 7. The smallest such number is 105.
3)
    
{"#2 and #3 as 6:8", "#0 and #1 as 9:3", "#3 and #0 as 7:5"}
Returns: {60, 20, 63, 84 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LangfordSequence

Brute Force, Recursion



Used in:

TCHS08 Finals

Used as:

Division I Level One

Writer:

andrewzta

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8723

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12046&pm=8723

Problem Statement

    

Let X be a set of n distinct integers. A sequence S of 2*n integers is called a Langford sequence for X if it satisfies both of the following properties:

  1. Each number in X occurs exactly twice in S.
  2. For each number i in X, there are exactly i numbers between the two occurrences of i in S.

For example, (2 3 1 2 1 3) is a Langford sequence for the set {1, 2, 3}. 1, 2 and 3 each occur exactly twice in the sequence. There is exactly 1 number between the two occurrences of 1 in the sequence, exactly 2 numbers between the two occurrences of 2, and exactly 3 numbers between the two occurrences of 3.

You are given a int[] a containing a set of distinct integers. Return the lexicographically first Langford sequence for this set. If there is no Langford sequence, return an empty int[] instead.

 

Definition

    
Class:LangfordSequence
Method:getFirst
Parameters:int[]
Returns:int[]
Method signature:int[] getFirst(int[] a)
(be sure your method is public)
    
 

Notes

-A int[] A comes before a int[] B lexicographically if A has a smaller integer at the first index at which they differ.
 

Constraints

-a will contain between 1 and 8 elements, inclusive.
-Each element of a will be between 0 and 16, inclusive.
-All elements of a will be distinct.
 

Examples

0)
    
{1, 2, 3}
Returns: {2, 3, 1, 2, 1, 3 }
The example from the problem statement.
1)
    
{0}
Returns: {0, 0 }
2)
    
{1, 2, 3, 4}
Returns: {2, 3, 4, 2, 1, 3, 1, 4 }
Another classical example of a Langford sequence.
3)
    
{1, 2, 3, 4, 5}
Returns: { }
There is no such sequence. To see this, imagine that the sequence exists. Note that the two 1's are at positions with the same parity (either both odd or both even), and so are the two 3's and the two 5's. This means either 4 out of 5 odd or 4 out of 5 even positions contain odd numbers. However, the positions that contain the two 2's do not have the same parity, and neither do the positions that contain the two 4's. So, there are either not enough odd positions or not enough even positions.
4)
    
{2, 0}
Returns: {2, 0, 0, 2 }
Note that the input will not necessarily be sorted.
5)
    
{0, 4, 13, 12, 8, 5, 2, 14}
Returns: { }
6)
    
{8, 0, 12, 6, 2, 4, 3, 13}
Returns: {12, 13, 2, 8, 3, 2, 4, 6, 3, 0, 0, 4, 8, 12, 6, 13 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ProcessorScheduling



Used in:


Used as:



Writer:


Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8708

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12166&pm=8708

Problem Statement

    

Introduction

You are working on a large, distributed scientific application. The application receives input at the beginning of execution, and then performs a number of computations. There are a number of components (or jobs) in the application, and some components are dependent on others meaning they can't be started until the others finish. The entire computation can best be expressed as a directed, acyclic graph. A node in the graph represents a component, which is dependent on the components from which it has edges. In addition to the graph topology, each node is labeled with a number giving the number of floating point operations (FLOPs) it will require.



You will be given a description of this graph as input. Additionally, you will be given the speeds of a number of machines, in FLOPs per millisecond. If a job is dependent on another job, and the two jobs are run on different machines, there must be a gap of transfer milliseconds between the end of the first job and the start of the second. If the two jobs are run on the same machine, there need be no gap.



Your task, naturally, is to run the computation as quickly as possible. Thus, you must return a schedule, assigning each component to one machine, and specifying the order to run the components on the machines. In your schedule, you may run one component for a while, pause it, run a different one, and then pick up where you left off with the first one. However, pausing and resuming takes some time. You may not transfer a component from one machine to another.



Input

The input will be given to you as a int[] machines, describing each machine in terms of FLOPs per millisecond, and a String[] jobs. Each element of jobs will be formatted as "FLOPs PAUSE JOB1 JOB2 ... JOBk". FLOPs gives you the number of FLOPs required by this job, while PAUSE tells you how long it will take to pause or resume (they take the same amount of time) the job, in milliseconds. JOBi gives you the ID of a job (indexed from 0) that must be completed prior to this job starting.



Output

You should return a String[] where each element is an interval to run a job on a machine. The elements should be formatted as:
    TIMEstart TIMEend J M
specifying a run of job J on machine M (indexed from 0) in the specified time interval.



Tests

Each test will be generated by first picking two constants uniformly: p in [0.0,0.05] and pow in [0,2]. transfer will be chosen uniformly in [1,1000]. The number of machines will then be chosen uniformly in [10,100], while the number of jobs will be chosen in [10,500000]. Each machine will have a speed uniformly chosen in [1000,10000]. Each job will have a pause time uniformly chosen in [1,10000]. The size of each job will be chosen in [1E3,1E9] according to a power law distribution with exponent pow. For each (i,j) such that i < j and i >= j-1000, job j will depend on i with probability p.

Scoring

For each test case, we will compute the number of milliseconds you take, beyond the lowest time on that test case out of all competitors. We will simply sum this over all test cases (and add 1 so that your score can't be 0). If the leader (with the lowest sum) has a sum of S, and you have a sum of T, your score will be sqrt(S/T)*100. If you fail on a test case, 1E9 will be added to your sum for that case.

Tools

ProcessorScheduling.java

ProcessorScheduling.jar

A very basic tool is provided to let you run tests locally. You should write a program that reads parameters from standard in, formatted like:
  M J transfer
  machine[0]
  machine[1]
  ...
  machine[M-1]
  jobs[0]
  jobs[1]
  ...
  jobs[J-1]
In other words, the first line contains three integers, the next M lines contain the machine input, and the final J lines contain the jobs input. You should output your result as:
  LEN
  result[0]
  result[1]
  ...
  result[LEN-1]
In other words, an integer followed by the elements of your return. The tool can be run from the command line as:
    java -Xmx1024M -jar ProcessorScheduling.jar <command> <seed>
<command> is the command for your executable, while <seed> defines the test paramters (the examples are seeds 1-10). Anything you print to standard error in your program will be shown on the console (be sure not to print anything other than what is specified above to standard out).
 

Definition

    
Class:ProcessorScheduling
Method:schedule
Parameters:int[], String[], int
Returns:String[]
Method signature:String[] schedule(int[] machines, String[] jobs, int transfer)
(be sure your method is public)
    
 

Notes

-If you allocate multiple intervals for one job, the pause and resume time will be included in the intervals. For example, if the pause time is one, and you allocate 1-5, 9-12, and 15-19 your program will run from 1-4, pause from 4-5, resume from 9-10 run from 10-11, pause from 11-12, resume from 15-16 and run from 16-19.
-The time limit is 15 seconds.
-The memory limit is 1024M.
-The thread limit is 32, including your primary thread. The machines have 8 cores, and thus you can potentially do much more computation by threading.
-If your solution is invalid in any way (overlapping intervals, starting a job before its requirements are finished, invalid formatting, etc) you will fail that case.
-The order of the jobs will be unchanged from the test case generation. Thus, they will be given to you sorted topologically.
-No job may run beyond time 1E10.
-The start and end times of each of your intervals must be integers.
 

Examples

0)
    
"1"
Returns: 
"p = 0.02945198102051495<br>
pow = 0.7984954674161717<br>
jobs = 217212<br>
machines = 84<br>
transfer = 307<br>
"
1)
    
"2"
Returns: 
"p = 0.022017740201681367<br>
pow = 0.0512270939535211<br>
jobs = 28793<br>
machines = 52<br>
transfer = 193<br>
"
2)
    
"3"
Returns: 
"p = 0.04084870687857926<br>
pow = 0.23936634704587667<br>
jobs = 284560<br>
machines = 20<br>
transfer = 581<br>
"
3)
    
"4"
Returns: 
"p = 0.043578829942208575<br>
pow = 0.3477121219273487<br>
jobs = 299706<br>
machines = 77<br>
transfer = 919<br>
"
4)
    
"5"
Returns: 
"p = 0.021666605038956104<br>
pow = 0.09719726359971026<br>
jobs = 61849<br>
machines = 44<br>
transfer = 653<br>
"
5)
    
"6"
Returns: 
"p = 0.049181906279069584<br>
pow = 1.2383634763946774<br>
jobs = 399664<br>
machines = 71<br>
transfer = 408<br>
"
6)
    
"7"
Returns: 
"p = 0.018161592536226474<br>
pow = 0.6116683327948489<br>
jobs = 348579<br>
machines = 74<br>
transfer = 211<br>
"
7)
    
"8"
Returns: 
"p = 0.020518731031700967<br>
pow = 1.0120276148220704<br>
jobs = 275119<br>
machines = 24<br>
transfer = 904<br>
"
8)
    
"9"
Returns: 
"p = 0.03382227207890865<br>
pow = 1.6639976727243304<br>
jobs = 58645<br>
machines = 59<br>
transfer = 522<br>
"
9)
    
"10"
Returns: 
"p = 0.013639577518082074<br>
pow = 0.04280968978315358<br>
jobs = 31997<br>
machines = 11<br>
transfer = 80<br>
"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RoundAboutCircle

Graph Theory, Simple Search, Iteration



Used in:

SRM 392

Used as:

Division I Level Two

Writer:

darnley

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8705

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11126&pm=8705

Problem Statement

    

N cells are located around a circle. Cells are numbered 1 through N in the clockwise direction.

Initially, you can place a token into any one of these cells.

In each turn, you look at the number of the cell containing the token and you calculate s, the sum of the digits in that number. You then move the token s cells clockwise.

This process continues until you move the token into a cell that already contained the token before. Your score is the number of cells that were visited by the token at least once during the process (including the initial cell).

Given N, return the maximal possible score you can get.

 

Definition

    
Class:RoundAboutCircle
Method:maxScore
Parameters:int
Returns:int
Method signature:int maxScore(int N)
(be sure your method is public)
    
 

Constraints

-N will be between 1 and 200000, inclusive.
 

Examples

0)
    
4
Returns: 3
The list of possible moves looks like this:

1->2

2->4

3->2

4->4



You can only visit 3 out of 4 cells, and there are two ways to do so: 1->2->4->4 and 3->2->4->4.
1)
    
5
Returns: 4
If you start on cell 5, the process will terminate after the first move. Otherwise, the token will travel along the loop 1->2->4->3->1 until the entire loop is visited, thus making your score equal to 4.
2)
    
17
Returns: 11
The longest path of the token is 5->10->11->13->17->8->16->6->12->15->4->8.
3)
    
566
Returns: 176

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CompanyRestructuring

Graph Theory, Greedy



Used in:

SRM 435

Used as:

Division I Level Three

Writer:

StevieT

Testers:

PabloGilberto , Olexiy , gawry , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8702

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13697&pm=8702

Problem Statement

    

A small company has recently been growing quickly and has decided that it needs to restructure its organisation. In the past, there were no permanent managers and project teams were formed on an ad-hoc basis depending on which employees were available at the time. This has lead to a situation where many of the employees have managed each other at some time in the past. Now that the company is bigger, it wants to impose a more formal hierarchical structure. The company is to be divided into divisions, each of which will be structured as a tree. One employee in each division will be assigned as the division leader and can be the permanent manager of some other employees. These employees can in turn manage futher employees, and so on. Each employee will belong to exactly one division and each employee in a division other than the division leader will have a permanent manager in the division.



The company knows that such a restructuring may lead to ill-feeling amongst the employees, particularly if an employee ends up being managed permanently by another employee that he or she has managed in the past. It has therefore come up with the following model to try to minimise this ill-feeling. If an employee has managed a person in the past, then he or she feels superior to that person. This is also transitive, so if A has managed B, and B has managed C, then A feels superior to both B and C, even if A has not directly managed C. More formally, an employee X0 feels superior to another employee Xk, if and only if there exists a sequence of employees X0, X1, X2 ... Xk, where employeee Xi has managed employee Xi+1 for each value of i < k. This can clearly lead to cases where each one of a pair of employees feels superior to the other and such a pair is termed mutually superior. These pairs of employees tend to spend a lot of time arguing about who is superior, so the company wishes to ensure they are separated in the new company structure. It has put the following restrictions on the structure of the new divisions.

  • The new permanent manager of an employee must have managed that employee in the past.
  • No employee can feel superior to his or her direct permanent manager.
  • No pair of mutually superior employees can have the same direct permanent manager.

The company wishes to end up with as few divisions as possible. You are given a String[] hasManaged, which details which employees have managed others in the past. Character j of element i will be 'Y' if employee i has managed employee j in the past and 'N' otherwise. Return the minimum number of divisions that the company must create in order to satisfy the above restrictions.

 

Definition

    
Class:CompanyRestructuring
Method:fewestDivisions
Parameters:String[]
Returns:int
Method signature:int fewestDivisions(String[] hasManaged)
(be sure your method is public)
    
 

Constraints

-hasManaged will contain between 1 and 50 elements, inclusive.
-Each element of hasManaged will contain the same number of characters as there are elements in hasManaged.
-Each character of hasManaged will be 'Y' or 'N'.
-Character i of element i of hasManaged will be 'N'.
 

Examples

0)
    
{"NNNN","NNYN","NNNN","YYYN"}
Returns: 1
There are no mutually superior employees here and only a single division is needed. There are 2 possible structures:



   3

  / \

 0   1

      \

       2



or



   3

 / | \

0  1  2

1)
    
{"NNYN","NNYN","YNNN","YYYN"}
Returns: 1
This case is similar to case 0), except now employees 0 and 2 are mutually superior, so cannot have the same manager. The second structure shown above is therefore invalid, but the first one is still possible.
2)
    
{"NYNNN","NNYNN","NNNYN","NNNNY","YNNNN"}
Returns: 5
Everybody feels superior to everybody else, so there is no way that any of them can work in the same division.
3)
    
{"NYNYYYNN"
,"NNNNYYNN"
,"NYNNYYNN"
,"NNYNYYNN"
,"NNNNNNNN"
,"NYYNYNNN"
,"YYNYYYNN"
,"YYNYYYYN"}
Returns: 1
4)
    
{"NYNYNNYYNYNNNYYNYNYY"
,"YNNNNNYYNNNYYNYNYNYY"
,"NNNNNNYYNNNYYNYNNNNY"
,"YNYNNNNYNNNYNNYNYNNY"
,"NYNNNNNYYYYNYNYYNNYN"
,"YYYYNNYNYNNNNNYYNYNY"
,"NNNNNNNNNNNYYNNNNNYY"
,"NNNNNNYNNNNYYNYNNNYN"
,"NYYYNNNYNNNNYYNYYNYY"
,"NNYNNNYYNNNNYNNNNNYY"
,"YYNNNYNNYNNNNYNNYNYY"
,"NNNNNNNYNNNNYNYNNNNY"
,"NNNNNNYNNNNYNNNNNNNN"
,"NNYNNNNNNNNYYNYNNYYN"
,"NNNNNNNNNNNYNNNNNNNY"
,"YNYYNYYNNNYYNNNNYNYY"
,"NYNNNNNYNYNYYYYNNNNY"
,"NNYNNNNYNYNYYYNNNNYY"
,"NNNNNNNYNNNYNNNNNNNY"
,"NNNNNNYYNNNYYNYNNNYN"}
Returns: 4
5)
    
{"NNNYNNNNNNNYNNNNNNNN"
,"NNNNNNYNNYNNNNNYNYYN"
,"YNNNNNYNYNNNNNNNNNNY"
,"YNNNNNNNNNNNNNNNNNNN"
,"NNYNNNYNYNNYNNYNNNNY"
,"NNNYNNNNNNNYNNYYYNYY"
,"NNYYNNNNYNNNNNNNNNNY"
,"NYNNNYNNYNNNYNYNYNNN"
,"NNNNNNNNNNNNNNNNNNNN"
,"YNNNNNNNNNNYNNYYNNYN"
,"NNYYNYNNYYNNNNYYNYNN"
,"NNNNNNNNYNNNNNNNNNNN"
,"NNNYYNYNYYYYNNNNYNYY"
,"NNYYNYNNYYYYNNNNNYNY"
,"NNYYYNNNYNNNNNNNNNNN"
,"YNNYYYNNNNNNNNYNYNYY"
,"NNNNYNYNNNNYNNYNNNNN"
,"YNNYYYYNNYNNYNNNYNYN"
,"YNNYYYYNYNNYNNYYYNNY"
,"YNYNNNNNYNNYNNNNNNNN"}
Returns: 2
6)
    
{"NNNNN","NNNNN","NNNNN","NNNNN","NNNNN"}
Returns: 5
Nobody has managed anybody in the past, so nobody can be a manager in the new structure either.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MagicLabeling

Graph Theory, Simple Math



Used in:

TCO08 Round 4

Used as:

Division I Level One

Writer:

ivan_metelsky

Testers:

PabloGilberto , legakis , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8676

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12014&pm=8676

Problem Statement

    

You are given a String[] graph, containing N elements and representing an undirected graph on N vertices. The j-th character in the i-th element of graph (which is the same as the i-th character in the j-th element of graph) is 'Y' if the i-th and j-th vertices of the graph are connected by an edge, and is 'N' otherwise.

You should label each vertex of the graph with an integer between 1 and M, inclusive, and then label each edge with the sum of its end vertices' labels. The labeling of vertices is called magic if each edge is labeled with the same integer. Two labelings of vertices are considered distinct if there's at least one vertex which has different labels in these labelings. Calculate the total count of distinct magic labelings of the given graph. Return this number modulo 1,000,003.

 

Definition

    
Class:MagicLabeling
Method:count
Parameters:String[], int
Returns:int
Method signature:int count(String[] graph, int M)
(be sure your method is public)
    
 

Constraints

-graph will contain between 1 and 50 elements, inclusive.
-Each element of graph will contain the same number of characters as the number of elements in graph.
-Each character in each element of graph will be 'Y' or 'N'.
-The i-th character in the i-th element of graph will be 'N' for all possible i.
-The i-th character in the j-th element of graph will be the same as the j-th character in the i-th element of graph for all possible i and j.
-M will be between 1 and 100, inclusive.
 

Examples

0)
    
{"NNNNN",
 "NNNNN",
 "NNNNN",
 "NNNNN",
 "NNNNN"}
100
Returns: 970003
Here we have 5 isolated vertices. As there are no edges at all, any labeling is magic. So the answer is 100^5 % 1000003 = 970003.
1)
    
{"NNNNN",
 "NNNNN",
 "NNNNY",
 "NNNNN",
 "NNYNN"}
100
Returns: 970003
An edge and 3 isolated vertices. With a single edge, any labeling is still valid.
2)
    
{"NYY",
 "YNN",
 "YNN"}
10
Returns: 100
Two edges joined at vertex 0. The labeling is magic if and only if vertices 1 and 2 have the same labels.
3)
    
{"NYNN",
 "YNNN",
 "NNNY",
 "NNYN"}
3
Returns: 19
Two separate edges. You can obtain the following sums on a single edge: 2 (1+1), 3 (1+2, 2+1), 4 (1+3, 2+2, 3+1), 5 (2+3, 3+2) and 6 (3+3). The number of ways to have the same sum on both edges is 1*1 + 2*2 + 3*3 + 2*2 + 1*1 = 19.
4)
    
{"NYY",
 "YNY",
 "YYN"}
15
Returns: 15
A triangle. The labeling is magic if and only if all vertices have the same labels.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Epidemic

Simulation



Used in:

TCO08 MM 2

Used as:

Division I Level One

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8632

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11131&pm=8632

Problem Statement

    You will be given a graph describing friendship between people. In the graph, each node represents a person, and each edge represents a friendship relationship. Your task is to come up with a scheme to prevent the spread of an epidemic disease by inoculating certain people, and reducing contact between some pairs of people.



The spread of the disease will be modelled by a simple simulation. If a person u with a friend v becomes infected on day D, then on day D+1 v becomes infected with probability pv. To combat the spread of the disease, you may both inoculate people, and decrease the probability along an edge (by reducing contact between people). If you chose to inoculate a person, you reduce that persons probability of being infected from pv to pv*X, for some constant X. Reducing the probability along an edge also reduces the infection probability to pv*Y, for some constant Y. These two effects are cumulative, so the infection probability can be pv*X*Y if you inoculate a person and reduce an edge.



Prior to the start of the epidemic, you may inoculate as many people as you like, but you may not reduce the probability along any edges. Once the epidemic starts, you may inoculate people and reduce edge probabilities as much as you want each day. If you inoculate a person on day D, then that person's chance of being infected is reduced on day D+1. The epidemic will start on day 1 with a seed population becoming infected.



Unfortunately, the disease may not be easy to diagnose, and if a person becomes infected on day D, you will not learn about it until day D+K, for some small constant K. Thus, a sample epidemic might go like this, with K = 2:
  • Prior to day 1, inoculate a few people
  • Day 1 - A and B become infected
  • Day 2 - The disease spreads to A's friend C
  • Day 3 - The disease spreads from C to D. You learn that A and B are infected, you inoculate C, D and reduce the probability along the edge from D to E.
  • Day 4 - The disease would have spread from D to E, but you reduced that edge's probability just in time. You learn that C is infected, but do nothing.
  • Day 5 - The epidemic is over, since no one new was infected on day 4. You learn that D is infected and inoculate F and G.
  • Day 6 - You see no new infections, and know that the epidemic is over.
Your task is to reduce the overall cost of the epidemic. Each person that is infected has a cost of infection, while each inoculation costs inoculation, and each edge reduction costs edgeReduce.



At the start of the simulation, you will be given a description of the friendship graph as a int[], g. Each pair of elements in g represents an edge. So for all i, g[2*i] and g[2*i+1] are joined by an (undirected) edge. Each person will also be categorized as low, medium, or high risk for infection. This will be done as follows, where rand() produces a random number in [0,1):
p = (pu-plow)/(phigh-plow)
if(p < 0.5 && rand() < 1-2*p) risk = low
else if(p > 0.5 && rand() < 2*p-1) risk = high
else risk = medium
This will be given to you as a int[], where 1 is low risk and 3 is high risk. After this (and some other) initial data is given, you should return a int[] representing the people to inoculate before the start of the epidemic. The simulation will then proceed, with your function being called every day, telling which people were infected K days ago. The first time it is called will be on day K+1. On each day, you should return a String[], where each element is either "<idx>" to inoculate person <idx> or "<u> <v>" to reduce the probability along an edge between <u> and <v>.



X and Y will be randomly chosen between 0.05 and 0.5. infection will be randomly chosen between 500 and 5000. inoculation will be randomly chosen between 100 and 1000. edgeReduce will be randomly chosen between 50 and 150. Two parameters plow and phigh will be chosen by picking two random numbers between 0.1 and 1, and ordering them. Each pv will then be chosen randomly between plow and phigh. K will be 0, 1 or 2. A seed population will be selected by choosing a random person, and all of his friends. This group of people will all become infected on day 1.



The graph will be generated by sampling from a much larger graph from an online social networking site. This will be done by first selecting M, the number of vertices to sample, between 100 and 100,000. A single seed vertex will by selected at random from the entire graph. To add each subsequent vertex, a random vertex will be chosen from those already in the sample and one of that vertex's friends will then be chosen at random. If that node has already been added, a new random vertex and a new random friend will be chosen until an unadded vertex is found. The edge set will consist of all edges in the original graph, both of whose endpoints are in the node set after all M nodes have been selected.



Your score for an individual test case will simply be the total cost incurred. Your overall score will be computed using relative scoring. For each test case we find the best (lowest) cost: BEST. We then take your score, YOU, and compute BEST/YOU. Summing over test cases gives your final score.



You can find more information about the graph sampling and generation here.
 

Definition

    
Class:Epidemic
Method:init
Parameters:int[], int[], int, int, int, int, double, double, double, double
Returns:int[]
Method signature:int[] init(int[] g, int[] risk, int infection, int inoculation, int edgeReduce, int K, double X, double Y, double plow, double phigh)
 
Method:day
Parameters:int[]
Returns:String[]
Method signature:String[] day(int[] infected)
(be sure your methods are public)
    
 

Notes

-Trying to inoculate a person twice or reduce an edge twice will incur twice the cost, with no added benefit.
-Once a person is inoculated or an edge reduced, it remains in that state till the end of the simulation.
-If a person becomes infected, he will never again be infected, and will only spread the epidemic on the day immediately after infection.
-If u and v are both infected on day D, and both are friends with w, then w will have two, independent chances to get infected on day D+1.
-People inoculated before the start of the simulation will have no effect on the seed group chosen to start the simulation.
-The memory limit is 1024M and the time limit is 20 seconds per test case.
-To understand the effect of K, imagine the case where X=0. If K=0, you could stop the disease by inoculating all the friends of people infected on the day you learn of their infection. If K=1, you would have to inoculate all the friends of friends of people infected on that day.
-You will only be given the edges once. Thus a graph with two connected nodes could be represented by {0,1} or {1,0}.
-All random choices are uniform and independent.
 

Constraints

-K will be 0, 1 or 2.
-X and Y will be in [0.05,0.5).
-infection will be in [500,5000].
-inoculation will be in [100,1000].
-edgeReduce will be in [50,150].
-The graph will contain between 100 and 100,000 nodes.
 

Examples

0)
    
"0 1"
Returns: 
"infection= 1183<br>
inoculation = 740<br>
edgeReduce = 121<br>
K = 0<br>
X = 0.31506782918463455<br>
Y = 0.22966148016863863<br>
p<sub>low</sub> = 0.280553917185094<br>
p<sub>high</sub> = 0.9159232446217902<br>
"
100 nodes, 208 edges, 2 nodes initially infected
1)
    
"1 2"
Returns: 
"infection= 2331<br>
inoculation = 309<br>
edgeReduce = 129<br>
K = 0<br>
X = 0.24815966181513233<br>
Y = 0.06152609613954225<br>
p<sub>low</sub> = 0.61915118868232<br>
p<sub>high</sub> = 0.6265059176199126<br>
"
1000 nodes, 4047 edges, 7 nodes initially infected
2)
    
"2 3"
Returns: 
"infection= 2807<br>
inoculation = 891<br>
edgeReduce = 85<br>
K = 1<br>
X = 0.4176383619072133<br>
Y = 0.10385742808532225<br>
p<sub>low</sub> = 0.429655474301043<br>
p<sub>high</sub> = 0.8522529103651292<br>
"
10000 nodes, 33103 edges, 7 nodes initially infected
3)
    
"3 4"
Returns: 
"infection= 501<br>
inoculation = 813<br>
edgeReduce = 150<br>
K = 0<br>
X = 0.44220946947987716<br>
Y = 0.12823522743365345<br>
p<sub>low</sub> = 0.24419978107506637<br>
p<sub>high</sub> = 0.4332017073338966<br>
"
100000 nodes, 670755 edges, 3 nodes initially infected
4)
    
"4 5"
Returns: 
"infection= 2353<br>
inoculation = 442<br>
edgeReduce = 139<br>
K = 0<br>
X = 0.24499944535060497<br>
Y = 0.07186938430993481<br>
p<sub>low</sub> = 0.711651651743351<br>
p<sub>high</sub> = 0.9238667101468845<br>
"
39932 nodes, 1400453 edges, 108 nodes initially infected
5)
    
"5 6"
Returns: 
"infection= 699<br>
inoculation = 652<br>
edgeReduce = 100<br>
K = 0<br>
X = 0.49263715651162626<br>
Y = 0.3286317821888024<br>
p<sub>low</sub> = 0.8190145293608756<br>
p<sub>high</sub> = 0.8794922843679077<br>
"
93461 nodes, 1411106 edges, 13 nodes initially infected
6)
    
"6 7"
Returns: 
"infection= 4253<br>
inoculation = 854<br>
edgeReduce = 144<br>
K = 1<br>
X = 0.21345433282603826<br>
Y = 0.187625374878841<br>
p<sub>low</sub> = 0.6280224192300305<br>
p<sub>high</sub> = 0.9075078847886737<br>
"
31355 nodes, 137044 edges, 5 nodes initially infected
7)
    
"7 8"
Returns: 
"infection= 1945<br>
inoculation = 591<br>
edgeReduce = 84<br>
K = 2<br>
X = 0.2346685792853087<br>
Y = 0.27770621333496587<br>
p<sub>low</sub> = 0.3165917779909993<br>
p<sub>high</sub> = 0.540334947695794<br>
"
61652 nodes, 671231 edges, 15 nodes initially infected
8)
    
"8 9"
Returns: 
"infection= 2420<br>
inoculation = 923<br>
edgeReduce = 85<br>
K = 2<br>
X = 0.35440044871017784<br>
Y = 0.4243994763629743<br>
p<sub>low</sub> = 0.3660937966336665<br>
p<sub>high</sub> = 0.630585328081465<br>
"
58852 nodes, 2257029 edges, 16 nodes initially infected
9)
    
"9 10"
Returns: 
"infection= 4174<br>
inoculation = 686<br>
edgeReduce = 81<br>
K = 1<br>
X = 0.17275619766273867<br>
Y = 0.059632180201209556<br>
p<sub>low</sub> = 0.6295556406256922<br>
p<sub>high</sub> = 0.8184365514653321<br>
"
70943 nodes, 2698437 edges, 4 nodes initially infected

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FixImage

Graph Theory, Greedy, Search



Used in:

SRM 396

Used as:

Division I Level Two

Writer:

asal1

Testers:

PabloGilberto , Olexiy , Andrew_Lazarev , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8615

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12168&pm=8615

Problem Statement

    You are given an image represented as a String[] alteredImage. alteredImage contains only '.' and '#' characters, representing white and black pixels, respectively. For the purposes of this problem, two black pixels are directly connected if they share a common edge. Two black pixels A and B are connected indirectly if there exists a path of black pixels A = P0, P1, ..., Pk = B, such that Pi and Pi + 1 are directly connected for all i. A block is a set of black pixels where every two pixels in the set are directly or indirectly connected, and no other black pixel can be added to the block while maintaining that property. A block is considered smooth if for each pair of pixels A and B in the block, there exists a path of black pixels between A and B with length equal to the manhattan distance between A and B.



The manhattan distance between two pixels A and B with coordinates (xA, yA) and (xB, yB), respectively, is the sum of the (absolute) differences of their coordinates(i.e. |xA - xB| + |yA - yB|).



Our friend sent us an image where all the black blocks are smooth. Due to some transmission errors, some black pixels were transmitted as white (but all white pixels remained white). Your task is to retrieve the original image. Find the minimum number of pixels you have to change from white to black so that every black block is smooth and return the original image in the same format as the altered one. The solution with the minimum number of changes will always be unique.
 

Definition

    
Class:FixImage
Method:originalImage
Parameters:String[]
Returns:String[]
Method signature:String[] originalImage(String[] alteredImage)
(be sure your method is public)
    
 

Constraints

-alteredImage will contain between 1 and 50 elements, inclusive.
-Each element of alteredImage will contain between 1 and 50 elements, inclusive.
-Each element of alteredImage will contain the same number of characters.
-alteredImage will contain only the characters '.' and '#'.
 

Examples

0)
    
{"....",
 ".##.",
 ".##.",
 "...."}
Returns: {"....", ".##.", ".##.", "...." }
This block is smooth.
1)
    
{".....",
 ".###.",
 ".#.#.",
 ".###.",
 "....."}
Returns: {".....", ".###.", ".###.", ".###.", "....." }
This block is not smooth. We need to make the center pixel black.
2)
    
{".......",
 ".###...",
 ".#..##.",
 ".###.#.",
 ".....#."}
Returns: {".......", ".###...", ".#####.", ".#####.", ".....#." }
This image consists of two blocks. The right one is smooth. We make the left one smooth by changing the white pixels inside it, but now our image consists of only one block which is not smooth. To make it smooth we need to change one more white square.
3)
    
 {".................",
 "#####.#..#..#####",
 "..#...#..#....#..",
 "..#...#..###..#..",
 "................."}
Returns: 
{".................",
"#####.#..#..#####",
"..#...#..#....#..",
"..#...#..###..#..",
"................." }
These smooth blocks spell out the word "TILT".
4)
    
 {"###.####",
  "#.#.#..#",
  ".#...#.#",
  ".#####.#",
  "......#.",
  "########"}
Returns: {"########", "########", "########", "########", "########", "########" }
5)
    
{"..###..",
 "..#.#..",
 "##...##",
 "#.....#",
 "#.....#",
 "#.....#",
 "##...##",
 "..#.#..",
 "..###.."}
Returns: 
{"..###..",
"..###..",
"##...##",
"##...##",
"##...##",
"##...##",
"##...##",
"..###..",
"..###.." }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PhoneNumbers

Brute Force



Used in:

TCO08 Qual 2

Used as:

Division I Level Two

Writer:

ivan_metelsky

Testers:

PabloGilberto , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8609

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12008&pm=8609

Problem Statement

    

You are given a String number containing the digits of a phone number. To help you memorize the number, you want to divide it into groups of contiguous digits. Each group must contain exactly 2 or 3 digits. There are three kinds of groups:

  • Excellent: A group that contains only the same digits. For example, 000 or 77.
  • Good: A group of 3 digits, 2 of which are the same. For example, 030, 229 or 166.
  • Usual: A group in which all the digits are distinct. For example, 123 or 90.

The quality of a group assignment is defined as 2 * (number of excellent groups) + (number of good groups). Divide the number into groups such that the quality is maximized, and return the result as a String, where each pair of consecutive groups is separated by a dash ('-'). If there are multiple ways to do this, return the one among them that results in the lexicographically earliest String.

 

Definition

    
Class:PhoneNumbers
Method:bestNumber
Parameters:String
Returns:String
Method signature:String bestNumber(String number)
(be sure your method is public)
    
 

Notes

-A String A comes before a String B lexicographically if A is a proper prefix of B, or if A has a smaller character at the first position where the strings differ. When comparing the characters, refer to the following list of characters in ascending order: '-', '0', '1', ..., '9'.
 

Constraints

-number will contain between 2 and 50 characters, inclusive.
-Each character in number will be a digit ('0'-'9').
 

Examples

0)
    
"5088638"
Returns: "50-88-638"
There are three possible ways to divide this number into groups: 508-86-38 (quality 0), 50-886-38 (quality 1) and 50-88-638 (quality 2). The last option is the best one.
1)
    
"0123456789"
Returns: "01-23-45-67-89"
No matter how you divide this number, the quality will be 0. Choose the division that comes earliest lexicographically.
2)
    
"09"
Returns: "09"
With a 2-digit phone number, there is only one choice.
3)
    
"54545454545454545454"
Returns: "54-545-454-545-454-545-454"
The best way to divide this number is to create six 3-digit good groups and one 2-digit usual group. Put the 2-digit group at the beginning to achieve the lexicographically earliest result.
4)
    
"00110001011100010111"
Returns: "00-11-00-010-11-10-00-101-11"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

OneWayStreets

Graph Theory



Used in:

TCO08 Round 2

Used as:

Division I Level One

Writer:

misof

Testers:

PabloGilberto , legakis , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8599

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12012&pm=8599

Problem Statement

    

The king of Absurdistan has become very angry, and thus he has decided to make an evil reform of the road network.

Currently, the network contains several towns, connected by some one-way and some two-way streets. The king's goal is to change all two-way streets into one-way streets. That is, for each currently present two-way street the king will pick one of the two directions, and make the street one-way in the chosen direction.

To make it even worse, the king has a simple goal he wants to achieve: After the reform the network must be so evil that once someone starts traveling along the roads, he will never be able to return back to the town where he started.

You will be given the current map as a String[] roads.

More precisely, the towns are numbered from 0 to N-1 for some N. The j-th character of the i-th element of roads is 'Y' if there is a direct road that allows us to travel from i to j, otherwise it will be 'N'. Each pair of towns is connected by at most one direct road. If the input contains a 'Y' both for a i->j road and for a j->i road, this means that the road between i and j is currently two-way.

Write a method that will return either "YES" or "NO" (quotes for clarity), depending on whether the king can achieve his evil goal.

 

Definition

    
Class:OneWayStreets
Method:canChange
Parameters:String[]
Returns:String
Method signature:String canChange(String[] roads)
(be sure your method is public)
    
 

Constraints

-roads will contain N elements, where N is between 2 and 50, inclusive.
-Each element of roads will contain exactly N characters.
-Each character in each element of roads will be either 'Y' or 'N'.
-For each i the i-th character of the i-th element of roads will be 'N'.
 

Examples

0)
    
{"NYN","NNY","NNN"}
Returns: "YES"
This map contains two roads: 0->1 and 1->2. Both roads are already one-way, so the king can't change anything. However, the map already has the desired property.
1)
    
{"NYN","YNY","NYN"}
Returns: "YES"
This map contains two roads: 0<->1 and 1<->2. Both roads are two-way. The king can change them to one-way streets 0->1 and 1->2, thus creating the situation from the previous example.
2)
    
{"NYNN","NNYN","YNNY","NNYN"}
Returns: "NO"
Roads: 0->1, 1->2, 2->0, and 2<->3. The king may change 2<->3 either to 2->3, or to 3->2. Neither of these changes will help him, as people will still be able to leave town 0 and return back via the route 0->1->2->0.
3)
    
{"NNN","NNN","NNN"}
Returns: "YES"
4)
    
{"NYYYY","YNYYY","YYNYY","YYYNY","YYYYN"}
Returns: "YES"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PseudoRandomKingdom

Dynamic Programming, Simple Math



Used in:

SRM 394

Used as:

Division I Level Three

Writer:

Xixas

Testers:

PabloGilberto , Olexiy , marek.cygan , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8593

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11128&pm=8593

Problem Statement

    

There are n cities in a kingdom, numbered 0 through n-1. Some pairs of cities are connected by bidirectional roads in such a way that one can traverse all the cities in the kingdom by following these roads. There are exactly n-1 roads. The configuration of the roads is given as a String[] g, where the i-th element is a single-space separated list of the cities connected to city i by direct roads.

A spendthrift king devised the following scheme for taxing the roads: Each road is assigned a random integer between 0 and cost, inclusive, where each such integer is equally likely. This integer is the cost in dollars of traversing the road. John lives in one of the cities in the kingdom, and he is not happy to learn about these taxes. His fiancee Mary lives in another city, and he wants to go visit her. However, he only has savings dollars to spend on taxes. Return the probability that John will be able to reach Mary, regardless of where they each live. In other words, return the probability that the cost of travel between any two cities in the kingdom will not be greater than savings.

 

Definition

    
Class:PseudoRandomKingdom
Method:probabilityOfHappiness
Parameters:String[], int, int
Returns:double
Method signature:double probabilityOfHappiness(String[] g, int cost, int savings)
(be sure your method is public)
    
 

Notes

-The returned value must be accurate to within a relative or absolute value of 1E-9.
 

Constraints

-g will contain n elements, where n is between 2 and 50, inclusive.
-Each element of g will contain between 0 and 50 characters, inclusive.
-Each element of g will be a single-space seperated list of distinct integers with no leading zeroes, each of which will be between 0 and n - 1, inclusive.
-i will not appear in the list g[i].
-i will appear in the list g[j] if and only if the number j will appear in the list g[i].
-g will represent a graph with the properties described in the problem statement.
-cost will be between 1 and 10, inclusive.
-savings will be between 0 and 500, inclusive.
 

Examples

0)
    
{"1 2",
 "0",
 "0 3",
 "2"}
1
2
Returns: 0.875
This is a path of length 3 so no more than two roads can have cost 1. We have 8 possible graphs in all and only the one where every road has a cost of 1 does not suit us. Thus the answer is 7/8.
1)
    
{"1 2 3 4 5 6",
 "0",
 "0",
 "0",
 "0",
 "0",
 "0"}
10
19
Returns: 0.903158288086044
Almost all graphs satisfy us.
2)
    
{"1 2 3 4 5 6",
 "0",
 "0",
 "0",
 "0",
 "0",
 "0"}
10
0
Returns: 5.644739300537775E-7
Now John does not have any savings at all.
3)
    
{"1",
 "0"}
10
500
Returns: 1.0000000000000002
4)
    
{"9 6",
 "6 4",
 "8",
 "5",
 "7 1",
 "8 3",
 "1 0 8",
 "4",
 "2 5 6",
 "0"}
9
26
Returns: 0.350862063

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ServiceFacilities

Graph Theory, Search



Used in:

TCO08 MM 1

Used as:

Division I Level One

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8579

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11130&pm=8579

Problem Statement

    

You are working on developing a planned city, meaning that you intend to plan and build certain elements of the infrastructure, like services, even before people take up residence. Several points of interest where development is planned, have been mapped.

It now needs to be determined where to build different types of major services, which might include things like airports, schools, hospitals, recycling centers, etc. The goal is to minimize the (Euclidean) distance someone might have to travel in order to reach any of these services. Each different service has been assigned a level of importance, and has an associated cost to build. Any service may be placed at as many locations as you like, within the constraints of your budget, however each service must be placed on at least one location, and no point of interest can contain more than one service.

Your method will be called, and will be given several parameters. int[]s x and y indicate each of the points of interest. You will also be given int[] serviceImportance, where each element indicates the importance of that service, as well as int[] serviceCost indicating the cost of building each service. Finally, int budget indicates the maximum total expenditure.

Test cases will be generated as follows (all ranges uniform):

  • Select the number of points, N = 50...200
  • Select the number of services, S = 4...15
  • Select N lattice points in the range (0, 0) - (100, 100)
  • Select each service imporance in the range 10...100
  • Select each service cost in the range 10...100
  • Select budget in the range minCost...(4*minCost), where minCost is the cost of building each service exactly once

For a proposed set of service locations, the overall convenience is scored by considering each lattice point (x,y) in the range (0,0) - (100,100), inclusive. For each point, we calculate a point-score by taking the sum over all i of serviceImportance[i] * distance[i], where distance[i] is the Euclidean distance from (x,y) to the nearest service of type i. The overall score is then calculated as the mean value of (point-score ^ 2).

Your return should be an array of integers, where each pair of integers represents a service type and a service location. For instance, return[2 * i] is a service number, and return[2 * i + 1] is a location (refering to the index of x and y).

Your goal is to place services in each location as to obtain an overall convenience score as low as possible. The overall scoring will be relative, so you will get BEST/YOU points for each test case, where BEST is the best score on that test case, and YOU is your score on that test case.

A visualizer is available.

 

Definition

    
Class:ServiceFacilities
Method:placeServices
Parameters:int[], int[], int[], int[], int
Returns:int[]
Method signature:int[] placeServices(int[] x, int[] y, int[] serviceImportance, int[] serviceCost, int budget)
(be sure your method is public)
    
 

Notes

-Time limit is 20 seconds, and memory limit is 1GB.
-There are 100 non-example test cases.
-The seeds for the examples are 1-10, in order.
 

Examples

0)
    
"1"
Returns: 
"Locations = 179<br>Services = 7<br>Budget = 673<br><br>Services:<ol><li>Importance = 84, Cost = 83</li><li>Importance = 70, Cost = 44</li><li>Importance = 95, Cost = 16</li><li>Importance = 56, Cost = 51</li><li>Importance = 87, Cost = 85</li><li>Importance = 45, Cost = 36</li><li>Importance = 67, Cost = 19</li></ol>"
1)
    
"2"
Returns: 
"Locations = 59<br>Services = 10<br>Budget = 1142<br><br>Services:<ol><li>Importance = 77, Cost = 36</li><li>Importance = 19, Cost = 50</li><li>Importance = 61, Cost = 23</li><li>Importance = 33, Cost = 29</li><li>Importance = 95, Cost = 58</li><li>Importance = 72, Cost = 22</li><li>Importance = 35, Cost = 50</li><li>Importance = 44, Cost = 19</li><li>Importance = 77, Cost = 91</li><li>Importance = 28, Cost = 50</li></ol>"
2)
    
"3"
Returns: 
"Locations = 145<br>Services = 10<br>Budget = 1520<br><br>Services:<ol><li>Importance = 41, Cost = 61</li><li>Importance = 64, Cost = 23</li><li>Importance = 76, Cost = 75</li><li>Importance = 23, Cost = 60</li><li>Importance = 28, Cost = 19</li><li>Importance = 13, Cost = 14</li><li>Importance = 55, Cost = 65</li><li>Importance = 100, Cost = 36</li><li>Importance = 91, Cost = 41</li><li>Importance = 64, Cost = 79</li></ol>"
3)
    
"4"
Returns: 
"Locations = 64<br>Services = 10<br>Budget = 1133<br><br>Services:<ol><li>Importance = 87, Cost = 31</li><li>Importance = 78, Cost = 53</li><li>Importance = 93, Cost = 15</li><li>Importance = 44, Cost = 90</li><li>Importance = 46, Cost = 60</li><li>Importance = 65, Cost = 18</li><li>Importance = 19, Cost = 78</li><li>Importance = 74, Cost = 95</li><li>Importance = 71, Cost = 15</li><li>Importance = 85, Cost = 45</li></ol>"
4)
    
"5"
Returns: 
"Locations = 87<br>Services = 7<br>Budget = 1275<br><br>Services:<ol><li>Importance = 74, Cost = 89</li><li>Importance = 34, Cost = 71</li><li>Importance = 31, Cost = 65</li><li>Importance = 10, Cost = 46</li><li>Importance = 37, Cost = 61</li><li>Importance = 30, Cost = 16</li><li>Importance = 87, Cost = 39</li></ol>"
5)
    
"6"
Returns: 
"Locations = 155<br>Services = 13<br>Budget = 2153<br><br>Services:<ol><li>Importance = 97, Cost = 21</li><li>Importance = 17, Cost = 39</li><li>Importance = 55, Cost = 19</li><li>Importance = 81, Cost = 54</li><li>Importance = 66, Cost = 88</li><li>Importance = 16, Cost = 77</li><li>Importance = 32, Cost = 81</li><li>Importance = 81, Cost = 22</li><li>Importance = 54, Cost = 85</li><li>Importance = 60, Cost = 53</li><li>Importance = 13, Cost = 19</li><li>Importance = 35, Cost = 88</li><li>Importance = 36, Cost = 34</li></ol>"
6)
    
"7"
Returns: 
"Locations = 194<br>Services = 12<br>Budget = 923<br><br>Services:<ol><li>Importance = 46, Cost = 38</li><li>Importance = 96, Cost = 11</li><li>Importance = 27, Cost = 39</li><li>Importance = 92, Cost = 42</li><li>Importance = 38, Cost = 26</li><li>Importance = 58, Cost = 13</li><li>Importance = 46, Cost = 90</li><li>Importance = 49, Cost = 54</li><li>Importance = 42, Cost = 50</li><li>Importance = 68, Cost = 79</li><li>Importance = 23, Cost = 87</li><li>Importance = 53, Cost = 12</li></ol>"
7)
    
"8"
Returns: 
"Locations = 152<br>Services = 10<br>Budget = 1259<br><br>Services:<ol><li>Importance = 70, Cost = 24</li><li>Importance = 76, Cost = 91</li><li>Importance = 41, Cost = 80</li><li>Importance = 28, Cost = 38</li><li>Importance = 63, Cost = 61</li><li>Importance = 96, Cost = 29</li><li>Importance = 72, Cost = 98</li><li>Importance = 80, Cost = 77</li><li>Importance = 30, Cost = 58</li><li>Importance = 10, Cost = 64</li></ol>"
8)
    
"9"
Returns: 
"Locations = 87<br>Services = 13<br>Budget = 2440<br><br>Services:<ol><li>Importance = 35, Cost = 73</li><li>Importance = 12, Cost = 64</li><li>Importance = 63, Cost = 96</li><li>Importance = 92, Cost = 81</li><li>Importance = 77, Cost = 49</li><li>Importance = 46, Cost = 77</li><li>Importance = 54, Cost = 80</li><li>Importance = 76, Cost = 98</li><li>Importance = 61, Cost = 90</li><li>Importance = 83, Cost = 82</li><li>Importance = 80, Cost = 10</li><li>Importance = 32, Cost = 60</li><li>Importance = 97, Cost = 51</li></ol>"
9)
    
"10"
Returns: 
"Locations = 73<br>Services = 14<br>Budget = 1100<br><br>Services:<ol><li>Importance = 96, Cost = 66</li><li>Importance = 87, Cost = 34</li><li>Importance = 52, Cost = 90</li><li>Importance = 100, Cost = 77</li><li>Importance = 73, Cost = 22</li><li>Importance = 100, Cost = 46</li><li>Importance = 69, Cost = 27</li><li>Importance = 48, Cost = 54</li><li>Importance = 43, Cost = 98</li><li>Importance = 31, Cost = 47</li><li>Importance = 70, Cost = 92</li><li>Importance = 38, Cost = 89</li><li>Importance = 42, Cost = 57</li><li>Importance = 93, Cost = 90</li></ol>"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheLuckySum

Dynamic Programming



Used in:

SRM 403

Used as:

Division I Level Three

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , Olexiy , marek.cygan , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8572

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12175&pm=8572

Problem Statement

    

John thinks 4 and 7 are lucky digits, and all other digits are not lucky. A lucky number is a number that contains only lucky digits in decimal notation.

Some numbers can be represented as a sum of only lucky numbers. Given an int n, return a int[] whose elements sum to exactly n. Each element of the int[] must be a lucky number. If there are multiple solutions, only consider those that contain the minimum possible number of elements, and return the one among those that comes earliest lexicographically. A int[] a1 comes before a int[] a2 lexicographically if a1 contains a smaller number at the first position where they differ. If n cannot be represented as a sum of lucky numbers, return an empty int[] instead.

 

Definition

    
Class:TheLuckySum
Method:sum
Parameters:int
Returns:int[]
Method signature:int[] sum(int n)
(be sure your method is public)
    
 

Constraints

-n will be between 1 and 1,000,000,000, inclusive.
 

Examples

0)
    
11
Returns: {4, 7 }
It is simple: 11 = 4 + 7.
1)
    
12
Returns: {4, 4, 4 }
Now we need three summands to get 12.
2)
    
13
Returns: { }
And now we can not get 13 at all.
3)
    
100
Returns: {4, 4, 4, 44, 44 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheSumOfLuckyNumbers

Dynamic Programming



Used in:

SRM 403

Used as:

Division II Level Three

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , Olexiy , marek.cygan , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8571

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12175&pm=8571

Problem Statement

    

John thinks 4 and 7 are lucky digits, and all other digits are not lucky. A lucky number is a number that contains only lucky digits in decimal notation.

Some numbers can be represented as a sum of only lucky numbers. Given an int n, return a int[] whose elements sum to exactly n. Each element of the int[] must be a lucky number. If there are multiple solutions, only consider those that contain the minimum possible number of elements, and return the one among those that comes earliest lexicographically. A int[] a1 comes before a int[] a2 lexicographically if a1 contains a smaller number at the first position where they differ. If n cannot be represented as a sum of lucky numbers, return an empty int[] instead.

 

Definition

    
Class:TheSumOfLuckyNumbers
Method:sum
Parameters:int
Returns:int[]
Method signature:int[] sum(int n)
(be sure your method is public)
    
 

Constraints

-n will be between 1 and 1,000,000, inclusive.
 

Examples

0)
    
11
Returns: {4, 7 }
It is simple: 11 = 4 + 7.
1)
    
12
Returns: {4, 4, 4 }
Now we need three summands to get 12.
2)
    
13
Returns: { }
And now we can not get 13 at all.
3)
    
100
Returns: {4, 4, 4, 44, 44 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GraphMancala

Graph Theory



Used in:

MM 28

Used as:

Division I Level One

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8562

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11133&pm=8562

Problem Statement

    You will be given a graph with nodes and edges. One node will be designated as a sink node. Each of the other nodes will have some number of pebbles on it. Your goal is to move all the pebbles to the sink node.



You will do this by repeatedly picking up all the pebbles on one node and finding a simple path leading away from that node (a simple path is one that follows edges and does not repeat any nodes). The length of the path should be equal to the number of pebbles in the node you selected. For instance, if you pick node A with 2 pebbles, you could select the path A->B->C. Once you have picked a path, you remove all the pebbles from the first node of the path, and add one pebble on each of the others. In the example above, you would place pebbles on nodes B and C.



The graph will be specified by N, the number of nodes in the graph, and by int[]'s u and v, where (u[i],v[i]) is an undirected edge in the graph. pebbles will give you the initial number of pebbles at each node, where pebbles[i] tells how many pebbles start at node i. The sink will always be node 0. You should return a String[] where each element specifies one move as a sequence of space-delimited integers. The first integer should specify the node to pick up pebbles from, followed by one node ID per pebble designating the path. For instance, "A B C" for the above example (substituting IDs for A, B, and C).



The graph will be generated by first selecting N uniformly in [10,1000]. N points will then be placed in the unit box from (0,0) to (1,1). The points will then be sorted by distance from the origin, so that node 0 is closest to the origin, while node N-1 is furthest. A constant C will be chosen uniformly in [0,0.2). For each pair of nodes u and v, an edge will then be formed between u and v if their distance is less than C. Each node other than the sink will start with between 1 and 10 pebbles, inclusive. If the graph ends up being disconnected, the generation is restarted from scratch.



Your score will start at 1. For each move that does not end at the sink (node 0), your score will be incremented (you want to end with a low score). At the end of all your moves, you must have moved all the pebbles to the sink. The overall scoring will be relative, so you will get BEST/YOU points for each test case, where BEST is the best score on that test case, and YOU is your score on that test case.
 

Definition

    
Class:GraphMancala
Method:move
Parameters:int, int[], int[], int[]
Returns:String[]
Method signature:String[] move(int N, int[] u, int[] v, int[] pebbles)
(be sure your method is public)
    
 

Notes

-The memory limit is 1024MB and the time limit is 10 seconds.
-Note that if you end up with too many pebbles at one node, you might not be able to make a move.
-You may not remove pebbles from the sink.
-A simple path may not be a circuit.
-Your return may not contain more than 100,000 elements.
 

Examples

0)
    
"240129208"
Returns: ""
The text file contains the four parameters, one per line: Download
1)
    
"293932108"
Returns: ""
Download
2)
    
"854143304"
Returns: ""
Download
3)
    
"153707217"
Returns: ""
Download
4)
    
"591303631"
Returns: ""
Download
5)
    
"195380701"
Returns: ""
Download
6)
    
"818605595"
Returns: ""
Download
7)
    
"175239594"
Returns: ""
Download
8)
    
"489759256"
Returns: ""
Download
9)
    
"153358147"
Returns: ""
Download

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

QuasiLatinSquares

Search



Used in:

SRM 392

Used as:

Division II Level Three

Writer:

darnley

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8561

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11126&pm=8561

Problem Statement

    

You are given two positive integers, n and d.

Create a square table of size n×n containing only integers between 0 and d-1, inclusive, such that each row and each column contains each number between 0 and d-1, inclusive, at least once.

Return this table as a String[] containing exactly n elements. Each element represents a single row of the table and contains a single space delimited list of the numbers in that row from left to right. The numbers must have no extra leading zeroes.

If there are multiple possible answers, return the one with the lexicographically smallest first element. If there is still a tie, return the one with the lexicographically smallest second element, etc.

 

Definition

    
Class:QuasiLatinSquares
Method:makeSquare
Parameters:int, int
Returns:String[]
Method signature:String[] makeSquare(int n, int d)
(be sure your method is public)
    
 

Notes

-A string S is greater than a string T lexicographically if T is a proper prefix of S, or if S has a greater character at the first position where the strings differ. A space character (' ') is considered smaller than any digit character ('0'-'9').
-It is guaranteed that there exists an answer for each valid input.
 

Constraints

-n will be between 1 and 10, inclusive.
-d will be between 1 and n, inclusive.
 

Examples

0)
    
3
3
Returns: {"0 1 2", "1 2 0", "2 0 1" }
If d equals n the desired table is called a Latin square. This is the lexicographically smallest Latin square of size 3.
1)
    
5
2
Returns: {"0 0 0 0 1", "0 0 0 0 1", "0 0 0 0 1", "0 0 0 0 1", "1 1 1 1 0" }
2)
    
5
4
Returns: {"0 0 1 2 3", "0 0 1 2 3", "1 1 0 3 2", "2 2 3 0 1", "3 3 2 1 0" }
3)
    
9
7
Returns: 
{"0 0 0 1 2 3 4 5 6",
"0 0 0 1 2 3 4 5 6",
"0 0 0 1 2 3 4 5 6",
"1 1 1 0 3 2 5 6 4",
"2 2 2 3 0 1 6 4 5",
"3 3 3 4 5 6 0 1 2",
"4 4 4 2 6 5 1 0 3",
"5 5 5 6 1 4 2 3 0",
"6 6 6 5 4 0 3 2 1" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SpecificPolyominoCovering

Search



Used in:

SRM 429

Used as:

Division I Level Three

Writer:

darnley

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8560

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13520&pm=8560

Problem Statement

    

You have an infinite number of the following two polyominoes:



A  A
AAAA


and



BB


You are NOT allowed to rotate them.

You are given a String[] region that represents a rectangular table filled with characters '.' and 'X'. The j-th character of the i-th element of region represents the cell at row i, column j of the table.

You need to cover (without overlapping) all the 'X' characters with the given polyominoes. Return a String[] that contains the same area with cells marked '.' left untouched, and cells marked 'X' changed to 'A' or 'B', according to the polyomino that covers the cell.

If there is no solution, return an empty String[].

If there are multiple solutions, return the one among them that comes first lexicographically. That is, you must minimize the first string, if there are still several solutions, minimize the second one, and so on.

 

Definition

    
Class:SpecificPolyominoCovering
Method:findCovering
Parameters:String[]
Returns:String[]
Method signature:String[] findCovering(String[] region)
(be sure your method is public)
    
 

Notes

-A string S is greater than a string T lexicographically if T is a proper prefix of S, or if S has a greater character at the first position where the strings differ.
 

Constraints

-region will contain between 1 and 50 elements, inclusive.
-Each element of region will contain between 1 and 50 characters, inclusive.
-All elements of region will contain the same number of characters.
-Each character in each element of region will be either '.' or uppercase 'X'.
 

Examples

0)
    
{"XXXX",
 "XXXX"}
Returns: {"ABBA", "AAAA" }
There are two possible coverings of the region:
BBBB
BBBB
and
ABBA
AAAA
The answer is the second covering since it is lexicographically smaller.
1)
    
{"X..XXXX..X",
 "XXXX..XXXX"}
Returns: {"A..ABBA..A", "AAAA..AAAA" }
There's only one way to cover this region.
2)
    
{"XXXXXX",
 "XXXXXX",
 "XXXXXX"}
Returns: {"ABBABB", "AAAABB", "BBBBBB" }
There's only room for one A-polyomino, and it is optimal to place it in the upper left corner.
3)
    
{"X..XX",
 "XXXXX"}
Returns: { }
The upper left 'X' must be covered with an A-polyomino (there is no room for a B-polyomino), but then there's no way to cover the rightmost cells.
4)
    
{"XXXXXXXXXX",
 "XXXXXXXXXX",
 "XXXXXXXXXX",
 "XXXXX..XXX",
 "XXXXXXXXXX",
 "XXXXXXXXXX",
 "XXXXXXXXXX"}
Returns: 
{"ABBAABBABB",
"AAAAAAAABB",
"ABBABBBBBB",
"AAAAA..ABB",
"ABBAAAAABB",
"AAAAABBABB",
"BBBBAAAABB" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LittleSquares

Dynamic Programming



Used in:

SRM 389

Used as:

Division I Level Three

Writer:

legakis

Testers:

PabloGilberto , Olexiy , Andrew_Lazarev , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8543

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11123&pm=8543

Problem Statement

    

Two people are playing a game, taking turns filling in squares on a piece of graph paper. On each turn, they can either fill in a single empty square or fill in a 2x2 block of 4 empty squares. Once all the squares in the grid are filled, the last player to have filled in a square is the winner.

The only restriction is that if we number the rows from top to bottom starting at zero, the top half of every 2x2 block that a player fills in during a turn must lie in an even-numbered row. For example, the following moves (in green) are legal:



while the following moves (in red) are illegal:



The current state of the grid will be given as a String[] state. Each element of state will be one row of the grid, and each character of each element of state will represent one square in the row. A '.' (period) represents an empty square, and a '#' represents a filled-in square.

From this current state, determine who can win the game assuming both people play optimally. If the next player to move can win return the String "first", otherwise, return the String "second" (all quotes for clarity).

 

Definition

    
Class:LittleSquares
Method:winner
Parameters:String[]
Returns:String
Method signature:String winner(String[] state)
(be sure your method is public)
    
 

Constraints

-states will contain an even number of elements, between 2 and 10, inclusive.
-The length of each element of states will be even and between 2 and 10, inclusive.
-The length of each element of states will be the same.
-Each character in states will be '.' (period) or '#'.
 

Examples

0)
    
{ "..",
  ".." }
Returns: "first"
On an empty 2x2 grid, the first player can win the game with a single move.
1)
    
{ "...#",
  "..##" }
Returns: "first"
If the first player draws a 2x2 square on the left side of the grid, she will lose. Likewise if she draws a 1x1 square in the rightmost open space. However if she draws a 1x1 square in any of the other four empty spaces, that will leave 4 empty squares to be filled in and she will be able to move last.
2)
    
{ "..",
  "..",
  "..",
  ".." }
Returns: "second"
If the first player draws a 2x2 square on her first move, the second player will draw another 2x2 square and win. If the first player draws a 1x1 square first, the second player will draw another in the other half of the grid, leaving 6 empty spaces that can only be filled in one at a time.
3)
    
{ "....",
  "...." }
Returns: "first"
The first player can draw a 2x2 square in the middle of the grid, leaving 4 empty spaces.
4)
    
{ ".##.",
  "#..#",
  "#..#",
  ".##." }
Returns: "second"
5)
    
{ "#.......",
  ".....##.",
  ".....##.",
  "........",
  "........",
  "........",
  "........",
  "#......#" }
Returns: "first"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PolygonCover

Dynamic Programming, Geometry, Graph Theory



Used in:

SRM 386

Used as:

Division I Level Two

Writer:

eleusive

Testers:

PabloGilberto , Olexiy , lovro , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8540

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11120&pm=8540

Problem Statement

    You're given several points in the cartesian plane. Return the smallest possible total sum of areas of a set of convex polygons such that each point is covered by at least one polygon. Moreover, the vertices of each polygon must all lie on the given points, and each polygon must have at least three sides. A point is covered by a polygon if the point lies in the polygon's interior or on its boundary.



The points are described by int[]s x and y, where (x[i],y[i]) is the location of the ith point.
 

Definition

    
Class:PolygonCover
Method:getArea
Parameters:int[], int[]
Returns:double
Method signature:double getArea(int[] x, int[] y)
(be sure your method is public)
    
 

Notes

-The returned value must be accurate to within a relative or absolute value of 1E-9.
-A polygon is convex if its edges only intersect at its vertices with each vertex sharing exactly two edges, and it's possible to complete a walk around the polygon by only making left turns.
-If two polygons with areas A and B overlap, then an area of A+B is contributed to the result.
 

Constraints

-x and y will each contain between 3 and 15 elements, inclusive.
-x and y will contain the same number of elements.
-Each element of x and y will be between -1000 and 1000, inclusive.
-No three points represented by x and y will lie on a common line.
 

Examples

0)
    
{0,10,0,-10}
{-10,0,10,0}
Returns: 200.0
The best way to cover these points is a square that has the four points as vertices.
1)
    
{-1,2,-2,0}
{-1,0,2,-1}
Returns: 2.0
The optimal solution here is to use two triangles; one triangle has vertices at points 0, 1, and 3 while the other triangle has vertices at points 0, 2, and 3.
2)
    
{2,0,-2,-1,1,0}
{0,2,0,-2,-2,1}
Returns: 3.0
3)
    
{1,0,-4,0,1,4}
{1,4,0,-4,-1,0}
Returns: 6.0

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SuperWatch

Graph Theory



Used in:

TCO08 Round 3

Used as:

Division I Level Three

Writer:

Olexiy

Testers:

PabloGilberto , legakis , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8525

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12013&pm=8525

Problem Statement

    

Year 3001. Your company needs to know if new model of watch is precise enough, so you need to run a small experiment. You'll take several watches, set them to "00:00", wait for a couple of years and then compute the watch imprecision which is equal to the largest difference between the two times shown on the watches. For example, if you've taken four watches and at the end of the experiment they've shown "11:11", "10:59", "11:02" and "11:13", then the biggest difference is 14 minutes (between "11:13" and "10:59").

To make the experiment a bit more interesting you've decided to give the watches to volunteers living in different time zones. The time zones have positive 0-based indices, so time zone number K is K hours ahead of yours. For example, 2:15 in your zone, 4:15 in zone 2 and 8:15 in zone 6 are the same moment of time. The watches of the volunteers were set according to the time zones they are from, so the watch for the volunteer from time zone X was set to X hours zero minutes at the beginning of the experiment. Before the start of the experiment you wrote down the time zones your volunteers are from, and at the end of the experiment each of the volunteers recorded the time shown on his watch. Unfortunately, you messed up the order of the records, so now you do not know which time zone corresponds to which volunteer. You are optimistic so you want to find the minimal possible imprecision under given data. Please note that the watches does not show date, so, for example, the difference between "23:50" and "00:10" can be only 20 minutes (or 23 hours and 40 minutes, if needed).

You will be given a String[] times, giving you the times recorded by volunteers. Each element of times is formatted as "HH:MM" (quotes for clarity), where HH is an hour between 00 and 23 and MM is a minute between 00 and 59. You will be also given a int[] zones, giving you the time zones for the volunteers. You are to assign each time zone to exactly one volunteer and return the minimal watch imprecision in minutes.

 

Definition

    
Class:SuperWatch
Method:smallestImprecision
Parameters:String[], int[]
Returns:int
Method signature:int smallestImprecision(String[] times, int[] zones)
(be sure your method is public)
    
 

Constraints

-times will contain between 2 and 40 elements, inclusive.
-zones will contain the same number of elements as times.
-Each element of times will be formatted as "HH:MM", where HH is a 2-digit integer between 00 and 23, inclusive, and MM is a 2-digit integer between 00 and 59, inclusive.
-Each element of zones will be between 0 and 23, inclusive.
 

Examples

0)
    
{"16:11", "15:59", "16:02", "16:13"}
{5, 5, 5, 5}
Returns: 14
The example from the problem statement, but all watches got a 5 hours time shift.
1)
    
{"12:11", "13:59", "19:02", "18:13"}
{1, 3, 7, 8}
Returns: 14
Assign zone 1 to watch 1, zone 3 to watch 2, zone 7 to watch 4 and zone 8 to watch 3 to achieve the same imprecision of 14 minutes.
2)
    
{"23:59", "00:02", "12:00", "08:01"}
{0, 0, 8, 12}
Returns: 3
It is near midnight now. The first two watches are in your zone, while the third and the fourth are offset by 12 and 8 hours, respectively.
3)
    
{"13:23", "11:54", "00:03", "22:22", "10:38"}
{1, 4, 13, 21, 13}
Returns: 256
4)
    
{ "00:00", "08:00", "16:00" }
{ 0, 0, 0 }
Returns: 960

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LargestGap

Brute Force, Greedy, String Manipulation



Used in:

SRM 402

Used as:

Division I Level Two

Writer:

srbga

Testers:

PabloGilberto , Olexiy , ivan_metelsky , Gassa

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8508

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12174&pm=8508

Problem Statement

    

Given a String[] board, concatenate all its elements, in order, to get a single string representing a circular board consisting of uppercase 'X' and '.' characters. "Circular" means that the first and the last characters on the board are consecutive. Maximal consecutive groups of 'X' characters form blocks and maximal consecutive groups of '.' characters form gaps. The size of the gap is the number of '.' characters in it.

You want to remove exactly one block from the board, getting a circular board of smaller size. For each possible block to be removed consider the board after its removal, construct an array of all gaps' sizes on the board and sort this array in non-ascending order. Choose the block for which the described array is lexicographically maximal (see notes for the description of lexicographical array comparison). Return the smallest 0-based index among all characters in this block (indices are taken in the concatenated string). In case of a tie choose the block which results in the smallest return value.

 

Definition

    
Class:LargestGap
Method:getLargest
Parameters:String[]
Returns:int
Method signature:int getLargest(String[] board)
(be sure your method is public)
    
 

Notes

-Let int[]s A and B contain the same number of elements. Then A is lexicographically larger than B if A contains a larger value at the first position where A and B differ.
 

Constraints

-board will contain between 1 and 50 elements, inclusive.
-Each element of board will contain between 1 and 50 characters, inclusive.
-board will contain only uppercase 'X' and '.' characters.
-board will contain at least two blocks.
 

Examples

0)
    
{".....X.X......."}
Returns: 5
Remove the first block.
1)
    
{"XXXX","....","XXXX","....","XXXX","...."}
Returns: 0

There are three blocks whose smallest indices are 0, 8, 16, respectively.

The board after removing each of the blocks look as follows:

  • The 1st block: "....XXXX....XXXX....".
  • The 2nd block: "XXXX........XXXX....".
  • The 3rd block: "XXXX....XXXX........".

All three results produce the same gaps array {8,4}. So we return the smallest index among {0,8,16}.

2)
    
{"XXX.........XX...........XX..X"}
Returns: 12
There are three gaps and three blocks (recall that the board is circular).
3)
    
{"XXX","X.....","....XX..XXXXXX","X........X..",".XXX."}
Returns: 32
There are 5 blocks and 5 gaps. There are two ways to maximize the largest gap, but only one of them also maxmizes the second largest one.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AirlineInternet

Geometry, Graph Theory, Search



Used in:

SRM 393

Used as:

Division I Level Three

Writer:

StevieT

Testers:

PabloGilberto , Olexiy , gawry , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8495

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11127&pm=8495

Problem Statement

    

An airline wishes to supply passengers with Internet access on its flights. To do so, it is going to to install powerful radio transceivers on all of its aircraft and at the airports it operates from. The airports will be connected to the Internet and the aircraft will be able to access the connection via a radio link to any airport that is within the range of its tranceiver. Aircraft will also be able to relay the Internet connection on to other aircraft that are within range, so even if an aircraft cannot communicate directly with an airport, it may be able to access the Internet via another aircraft. The cost of the radio equipment is proportional to its range and the airline wishes to supply the Internet connection at minimal cost. It therefore wants your help in determining the minimum transceiver range required such that all of the aircraft can access the Internet all of the time.

The area that the airline operates in is represented as a 2-D cartesian plane. You are given a String[] airports containing the locations of the airports that the airline operates from. Each element will contain two space-separated integers, formatted without leading zeros, giving the x- and y-coordinates of an airport. You are also given the flight-schedule in a String[] flights. Each element of flights describes a single flight and will be formatted "<start> <destination> <take-off time> <landing time>" (quotes for clarity). All elements are integers formatted without leading zeros. <start> and <destination> reference zero-based indexes of airports in airports. The aircraft starts out at the airport referenced by <start> at time <take-off time>, and flies in a straight line at constant speed to the airport referenced in <destination>, arriving at <landing time>. All radio tranceivers have the same range R and an aircraft can communicate with an airport or another aircraft if the in-plane distance between the two is no greater than R. An aircraft can access the Internet if it can either communicate with an airport, or it can communicate with another aircraft that can access the Internet (directly or indirectly). Return a double containing the minimum value of R which ensures that all aircraft can access the Internet at all times.

 

Definition

    
Class:AirlineInternet
Method:minimumRange
Parameters:String[], String[]
Returns:double
Method signature:double minimumRange(String[] airportLocations, String[] flights)
(be sure your method is public)
    
 

Notes

-Your return value must be accurate to within an absolute or relative tolerance of 1E-9.
 

Constraints

-airportLocations will contain between 2 and 10 elements, inclusive.
-Each element of airportLocations will contain 2 space-separated integers, formatted without leading zeros, between 0 and 1000, inclusive.
-The elements of airportLocations will be distinct.
-flights will contain between 1 and 20 elements, inclusive.
-Each element of flights will be formatted "<start> <destination> <take-off time> <landing time>" (quotes for clarity).
-<start> and <destination> will be integers, formatted without leading zeros, between 0 and N-1, inclusive, where N is the number of elements in airportLocations.
-<take-off time> and <landing time> will be integers, formatted without leading zeros, between 0 and 1000, inclusive.
-In each element of flights, <start> and <destination> will be distinct and <take-off time> will be strictly less than <landing time>.
 

Examples

0)
    
{"0 0","100 0"}
{"0 1 0 100"}
Returns: 50.0
A single aircraft flies between two airports. It is farthest from an airport when it is exactly halfway between them, so the minimum required range is half the distance between the two airports.
1)
    
{"0 0","100 0"}
{"0 1 0 100","0 1 25 125","0 1 50 150","0 1 75 175"}
Returns: 25.0
This time, four aircraft fly between the same two airports, setting off at intervals of 25 time units. The aircraft closer to the airports can relay the connection to those farther away, so the minimum required range is shorter.
2)
    
{"25 100","0 50","90 150","22 22","60 1","95 8","12 40"}
{"0 1 0 500","2 5 10 300","2 0 100 200"
,"3 6 150 400","4 5 50 450","5 1 0 300"
,"2 6 10 100"}
Returns: 64.28201130009927
3)
    
{"0 0","50 0","100 0"}
{"0 1 0 100"}
Returns: 25.0
All airports have radio transceivers, even if no aircraft fly to or from them.
4)
    
{"417 262","519 592","941 778"}
{"0 1 376 534","0 2 603 763","1 0 137 431"
,"0 1 525 583","2 1 367 551","0 1 953 996"
,"0 1 668 886"}
Returns: 246.618769031594
5)
    
{"101 591","283 183","346 696","436 638","738 46"}
{"3 0 855 890","2 0 260 698","3 4 229 743"
,"1 2 519 898","3 1 863 955","4 0 407 993"
,"2 4 872 969","0 3 320 663"}
Returns: 298.18759041416865
6)
    
{"152 998","656 487","75 999","913 535"}
{"1 0 347 530","0 3 75 819","3 1 893 935"
,"1 0 971 992","2 0 471 887","2 0 924 955"}
Returns: 358.8652253980556

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MarbleCollectionGame

Dynamic Programming, Graph Theory



Used in:

SRM 391

Used as:

Division II Level Three

Writer:

stone

Testers:

PabloGilberto , Olexiy , lovro , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8488

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11125&pm=8488

Problem Statement

    

A marble game is played on a board, each cell of which may contain a number of marbles. Your task is to collect as many marbles as possible using a robot on the board. The layout of the board is given in the String[] board, where each cell is marked with a digit ('0'-'9'), '#', 'U' or 'L'. Each digit represents the number of marbles in that cell. There are no marbles in cells that are not marked with digits.

The robot starts in the upper left cell, which is the first character of the first element of board. During each turn, it can move according to the following rules:

  • The robot can't move out of the board.
  • The robot can't enter a cell marked '#'.
  • The robot may move either right or down one step from any cell.
  • The robot may move up one step from a cell marked 'U'.
  • The robot may move left one step from a cell marked 'L'.

When the robot enters a cell for the first time, it collects all the marbles from that cell. That cell will no longer contain any marbles for the rest of the game. Return the maximum total number of marbles the robot can collect.

 

Definition

    
Class:MarbleCollectionGame
Method:collectMarble
Parameters:String[]
Returns:int
Method signature:int collectMarble(String[] board)
(be sure your method is public)
    
 

Constraints

-board will contain between 1 and 20 elements, inclusive.
-Each element of board will contain between 1 and 20 characters. inclusive.
-Each element of board will contain the same number of characters.
-Each element of board will contain only digits ('0'-'9'), '#', 'U' and 'L'.
-The first character of the first element of board will not be '#'.
 

Examples

0)
    
{"7"}
Returns: 7
1)
    
{"0",
 "8"}
Returns: 8
2)
    
{"264",
 "3LL"}
Returns: 15
The best route is right, right, down, left and left.
3)
    
{"8U4L9",
 "0183U",
 "U8#38",
 "2158#",
 "L65U7"}
Returns: 44
4)
    
{"039LLLU",
 "953348#",
 "0L87#29",
 "718#4#U",
 "594U196"}
Returns: 55

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

UnderscoreJustification

Greedy, String Manipulation



Used in:

SRM 385

Used as:

Division I Level One , Division II Level Two

Writer:

Petr

Testers:

PabloGilberto , Olexiy , gawry , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8482

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10810&pm=8482

Problem Statement

    

Most word processors available today allow several standard ways to format lines in a paragraph. One of those ways is to 'justify' each line to a given width. The precise definition for that operation is as follows:

Assume that a line of text consists of several words separated by spaces (for simplicity, there will be no punctuation). Define a gap as the sequence of spaces between a pair of adjacent words. When reformatting a line, each gap can be replaced with a gap of a different non-zero length. The line is said to be justified to width w if it is exactly w characters long, has no leading or trailing spaces, and all gaps are as evenly distributed as possible. This means that the gaps should all be of equal length, or, if that is not possible, the difference in length between the longest and smallest gaps must be 1.

To better illustrate the results of the justification operation, we will use underscores ('_') in place of spaces.

Obviously, the above rules don't uniquely define the result of a justification. If there are multiple ways to justify a line of text, the one that comes earliest lexicographically is used. Note that an underscore comes after uppercase letters but before lowercase letters in the ASCII ordering.

You are given a String[] words containing all the words in a line of text. The words are given in the order that they appear in the line. Return the line of text justified to the given width, using underscores as spaces.

 

Definition

    
Class:UnderscoreJustification
Method:justifyLine
Parameters:String[], int
Returns:String
Method signature:String justifyLine(String[] words, int width)
(be sure your method is public)
    
 

Notes

-Note that you must make all the gaps have equal length if possible. Only if that is impossible, the longest gap will be one longer than the shortest.
-Remember that 'A' < 'B' < 'C' < ... < 'Z' < '_' < 'a' < 'b' < 'c' < ... < 'z'.
-A string is lexicographically smaller than another string if it contains a smaller character in the first position where they differ.
 

Constraints

-words will contain between 2 and 10 elements, inclusive.
-Each element of words will contain between 1 and 10 characters, inclusive.
-Each element of words will contain only letters ('A'-'Z', 'a'-'z').
-width will be between 3 and 200, inclusive.
-width will be greater than or equal to len+n-1, where n is the number of elements in words, and len is the total number of characters in words, to allow at least one space between adjacent words.
 

Examples

0)
    
{"A", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"}
50
Returns: "A___quick__brown__fox__jumps__over__the__lazy__dog"
We have 7 groups of 2 underscores and 1 group of 3 underscores to put between our words. If the first gap contains 2 underscores, then the string would start with "A__q", which is lexicographically larger than "A___", so it's advantageous to put 3 underscores in the first gap.
1)
    
{"Alpha", "Beta", "Gamma", "Delta", "Epsilon"}
32
Returns: "Alpha_Beta_Gamma__Delta__Epsilon"
There are six possible variants:

Alpha_Beta_Gamma__Delta__Epsilon

Alpha_Beta__Gamma_Delta__Epsilon

Alpha_Beta__Gamma__Delta_Epsilon

Alpha__Beta_Gamma_Delta__Epsilon

Alpha__Beta_Gamma__Delta_Epsilon

Alpha__Beta__Gamma_Delta_Epsilon

The former is the lexicographically smallest one.
2)
    
{"Hello", "world", "John", "said"}
29
Returns: "Hello____world___John____said"
Sometimes it's better to mix large and small groups of underscores.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

InformFriends

Dynamic Programming, Graph Theory



Used in:

SRM 388

Used as:

Division I Level Two

Writer:

bmerry

Testers:

PabloGilberto , Olexiy , marek.cygan , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8473

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11122&pm=8473

Problem Statement

    

You wish to share as many facts as possible with a group of N people, but you only have time to tell one fact to each person in the group. When you tell someone a fact, you also instruct them to tell all their friends. However, the friends do not tell their friends: if A and B are friends, B and C are friends, but A and C are not friends, then after telling the fact to A it will be passed on to B but not to C. You must tell each fact to enough people so that every person either hears the fact from you, or is a friend of someone who heard it from you.

friends contains N strings of N characters, each of which is either 'Y' or 'N'. The jth character of the ith element is 'Y' if members i and j are friends, and 'N' otherwise. Determine the maximum number of facts that can be shared with every person in the group.

 

Definition

    
Class:InformFriends
Method:maximumGroups
Parameters:String[]
Returns:int
Method signature:int maximumGroups(String[] friends)
(be sure your method is public)
    
 

Constraints

-friends will contain exactly N elements, where N is between 1 and 15, inclusive.
-Each element of friends will contain exactly N characters.
-Each character in friends will be either 'Y' or 'N'.
-For i and j between 0 and N - 1, inclusive, character j of element i of friends will be the same as character i of element j.
-For i between 0 and N - 1, inclusive, character i of element i of friends will be 'N'.
 

Examples

0)
    
{"NYYN",
 "YNYY",
 "YYNY",
 "NYYN"}
Returns: 3
Tell one fact to people 0 and 3, one fact to 1, and one fact to 2.
1)
    
{"NYYN",
 "YNYN",
 "YYNN",
 "NNNN"}
Returns: 1
Person 3 has no friends, and so can learn only one fact directly from you.
2)
    
{"NYNNNY",
 "YNYNNN",
 "NYNYNN",
 "NNYNYN",
 "NNNYNY",
 "YNNNYN"}
Returns: 3
Provide facts A, B, C, A, B, C to the six people in order. Each will receive one fact directly and one from each neighbor.
3)
    
{"NYNY",
 "YNYN",
 "NYNY",
 "YNYN"}
Returns: 2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CandyGame

Dynamic Programming, Graph Theory, Greedy



Used in:

SRM 408

Used as:

Division I Level Two

Writer:

connect4

Testers:

PabloGilberto , Olexiy , Andrew_Lazarev , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8462

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12180&pm=8462

Problem Statement

    

Your brother is playing a new game he received for his birthday. The game takes place on an acyclic, undirected graph, with pieces of candy located on some of the nodes. On each turn, your brother picks a node with at least 2 pieces of candy on it. He then picks up 2 pieces of candy from that node, eats one piece, and places the other piece on an adjacent node. If at any time there is a piece of candy on the target node, then the game is over and your brother wins. If he cannot put candy on that node through any sequence of moves, he loses. Your brother is smart, and so if there is a winning sequence of moves he will find it.

You enjoy frustrating your brother and want to make him lose the game. The graph will be given as a String[]. The j-th character of element i will be 'Y' if nodes i and j are connected in the graph; otherwise, it will be 'N'. Return the maximum number of pieces that can be placed on the board without your brother being able to win; if more than 2,000,000,000 pieces can be placed on the board without your brother winning, return -1 instead.

 

Definition

    
Class:CandyGame
Method:maximumCandy
Parameters:String[], int
Returns:int
Method signature:int maximumCandy(String[] graph, int target)
(be sure your method is public)
    
 

Constraints

-graph will contain N elements, where N is between 1 and 50, inclusive.
-Each element of graph will contain exactly N characters.
-Each character in graph will be either 'Y' or 'N'.
-In graph, the j-th character of element i will equal the i-th character of element j.
-The i-th character of the i-th element of graph will be 'N'.
-The graph represented by graph will have no cycles.
-target will be between 0 and N-1, inclusive.
 

Examples

0)
    
{"NYN", "YNY", "NYN"}
1
Returns: 2
The graph is a straight line:
0-1-2
With node 1 as the target, we can only put one piece of candy each on nodes 0 and 2. If you place a second piece on either, your brother can eat one and move the other to node 1.
1)
    
{"NYN", "YNY", "NYN"}
2
Returns: 3
The same graph as example 0, but now node 2 is the target. The optimal strategy places 3 pieces of candy on node 0.
2)
    
{"NYYY", "YNNN", "YNNN", "YNNN"}
0
Returns: 3
3)
    
{"NYYY", "YNNN", "YNNN", "YNNN"}
1
Returns: 4
4)
    
{"NYNNNYN",
 "YNYNYNN",
 "NYNYNNN",
 "NNYNNNN",
 "NYNNNNN",
 "YNNNNNY",
 "NNNNNYN"}
0
Returns: 11
5)
    
{"NYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
 "YNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
 "NYNYNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
 "NNYNYNNNNNNNNNNNNNNNNNNNNNNNNNNN",
 "NNNYNYNNNNNNNNNNNNNNNNNNNNNNNNNN",
 "NNNNYNYNNNNNNNNNNNNNNNNNNNNNNNNN",
 "NNNNNYNYNNNNNNNNNNNNNNNNNNNNNNNN",
 "NNNNNNYNYNNNNNNNNNNNNNNNNNNNNNNN",
 "NNNNNNNYNYNNNNNNNNNNNNNNNNNNNNNN",
 "NNNNNNNNYNYNNNNNNNNNNNNNNNNNNNNN",
 "NNNNNNNNNYNYNNNNNNNNNNNNNNNNNNNN",
 "NNNNNNNNNNYNYNNNNNNNNNNNNNNNNNNN",
 "NNNNNNNNNNNYNYNNNNNNNNNNNNNNNNNN",
 "NNNNNNNNNNNNYNYNNNNNNNNNNNNNNNNN",
 "NNNNNNNNNNNNNYNYNNNNNNNNNNNNNNNN",
 "NNNNNNNNNNNNNNYNYNNNNNNNNNNNNNNN",
 "NNNNNNNNNNNNNNNYNYNNNNNNNNNNNNNN",
 "NNNNNNNNNNNNNNNNYNYNNNNNNNNNNNNN",
 "NNNNNNNNNNNNNNNNNYNYNNNNNNNNNNNN",
 "NNNNNNNNNNNNNNNNNNYNYNNNNNNNNNNN",
 "NNNNNNNNNNNNNNNNNNNYNYNNNNNNNNNN",
 "NNNNNNNNNNNNNNNNNNNNYNYNNNNNNNNN",
 "NNNNNNNNNNNNNNNNNNNNNYNYNNNNNNNN",
 "NNNNNNNNNNNNNNNNNNNNNNYNYNNNNNNN",
 "NNNNNNNNNNNNNNNNNNNNNNNYNYNNNNNN",
 "NNNNNNNNNNNNNNNNNNNNNNNNYNYNNNNN",
 "NNNNNNNNNNNNNNNNNNNNNNNNNYNYNNNN",
 "NNNNNNNNNNNNNNNNNNNNNNNNNNYNYNNN",
 "NNNNNNNNNNNNNNNNNNNNNNNNNNNYNYNN",
 "NNNNNNNNNNNNNNNNNNNNNNNNNNNNYNYN",
 "NNNNNNNNNNNNNNNNNNNNNNNNNNNNNYNY",
 "NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNYN"}
0
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TreeMaps

Simulation



Used in:

TC China 08 - Finals

Used as:

Division I Level Three

Writer:

jbernadas

Testers:

PabloGilberto , Andrew_Lazarev , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8461

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13678&pm=8461

Problem Statement

    

At our company, the hard drive capacity of the file servers is very small, which forces the administrators to delete files frequently to recover hard disk space. Some time ago, they used the operating system interface to traverse the file system from the root directory to the files, deleting big old files in the process.



The file system is structured as a rooted tree, specified by parent, size and type. The ID of a node is its 0-based position inside parent. For example, the 3rd node has ID=3. The k-th node is a file if type[k] is 'F' and is a directory if type[k] is 'D'. The parent of the k-th node is the parent[k]-th node, which is guaranteed to be a directory. The tree's root is node 0 and its parent is -1, indicating that it is not contained inside any other node. Finally, if the k-th node is a file, its size is size[k]; if the k-th node is a directory, size[k] will be equal to the sum of the sizes of its immediate child nodes.



Last week, a graphical interface to look at the entire file system at once was released. In this interface, a rectangle of width x height units with its lower-left corner at (0,0) and its upper-right corner at (width, height) is split horizontally between directories and files contained by the root directory. Then, each root's subdirectory is split vertically between its children, and so on, switching the split direction at each level. To split a rectangle horizontally, split its width between its children proportionally to their sizes, ordering the children left to right in increasing order by ID. To split a rectangle vertically, split its height between its children proportionally to their sizes, ordering the children from bottom to top in increasing order by ID.



For example, given the following file system structure (see example 0):





Then, given the blue rectangle with width=20 and height=8, the root node divides it between all its children, giving the directory 3 a bigger part because its total size is greater than the files 1, 2 and 8. This division is made horizontally, where the x axis goes from left to right. This division can be seen in the following image:





Then, the directory 3 divides its red rectangle between its children, ordering them from bottom to top in increasing order by ID. This division is made vertically, where the y axis goes from bottom to top. This division can be seen in the following image:





When an administrator clicks a file's rectangle, the file is erased and the rectangles are recalculated. Given the position of many clicks made by an administrator, return a int[] with the same number of elements as px, where the k-th element is the ID of the file erased by the click made at (px[k], py[k]). It is guaranteed that the administrator always clicks strictly inside some file's rectangle.



 

Definition

    
Class:TreeMaps
Method:eraseFiles
Parameters:String, int[], int[], int, int, int[], int[]
Returns:int[]
Method signature:int[] eraseFiles(String type, int[] parent, int[] size, int width, int height, int[] px, int[] py)
(be sure your method is public)
    
 

Constraints

-type will contain N elements, where N is between 2 and 50, inclusive.
-Each character of type will be either 'F' or 'D'.
-At least one character in type will be 'F'.
-The first character of type will be 'D'.
-parent will contain exactly N elements.
-Each element of parent will be between 0 and N-1, inclusive, except for the first element which will be equal to -1.
-Each node that appears in parent will be a directory.
-The structure defined by parent will be a rooted tree at 0. This means that there will be no cycles and all nodes can reach the root by following the parent links.
-size will contain exactly N elements.
-Each element of size will be between 1 and 1000, inclusive.
-Each element of size where the corresponding element of type is 'D' will be equal to the sum of the sizes of its children.
-width will between 2 and 1000, inclusive.
-height will between 2 and 1000, inclusive.
-px will contain M elements, where M is between 1 and the number of 'F's in type, inclusive.
-Each element of px will be between 0 and width, exclusive.
-py will contain exactly M elements.
-Each element of py will be between 0 and height, exclusive.
-There will be no k such that the point (px[k], py[k]) lies at a distance less than 1E-6 from a file rectangle's border.
 

Examples

0)
    
"DFFDFFFFF"
{-1, 0, 0, 0, 3, 3, 3, 3, 0}
{10, 2, 2, 4, 1, 1, 1, 1, 2}
20
8
{12, 12}
{1, 4}
Returns: {4, 6 }
The file system structure and the initial division of this example can be seen in the problem statement. Observe that after erasing file 4 with the first click, the image is recalculated and the point (12,4) is not in a rectangle's boundary anymore.
1)
    
"DFFDFFFFF"
{-1, 0, 0, 0, 3, 3, 3, 3, 0}
{10, 2, 2, 4, 1, 1, 1, 1, 2}
20
8
{12, 12, 12, 12, 12}
{1, 1, 1, 1, 1}
Returns: {4, 5, 6, 7, 2 }
The file system structure and the initial division of this example can be seen in the problem statement. The first four clicks erase all the files in directory 3. Note that after clearing a directory, the system gives it no area, so the fifth click erases file 2.
2)
    
"DDDFFDFFF"
{-1, 0, 0, 1, 1, 2, 2, 5, 5}
{10, 4, 6, 2, 2, 5, 1, 2, 3}
50
50
{16, 41, 32}
{10, 38, 29}
Returns: {3, 8, 7 }
3)
    
"DFFFFD"
{-1, 5, 5, 5, 5, 0}
{10, 4, 2, 3, 1, 10}
20
20
{1, 1}
{2, 18}
Returns: {1, 4 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheSquares

Dynamic Programming



Used in:

SRM 381

Used as:

Division I Level Three

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8418

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10804&pm=8418

Problem Statement

    

Little John does a lot of programming, and is therefore very strange. Recently, he started talking with some geometrical figures. Squares are his favorite ones, and he gives names to them. Yes, it is very strange, but don't forget that John is a programmer!

John has drawn many squares on a big sheet of paper and each square has its own name. Now John is looking for a sequence of k squares such that each square except the first one lies inside the previous square in the sequence.

One square lies inside another one if all its points are inside the bigger square, possibly on a boundary.

You are given String[]s x, y, lengths and names, and an int k. For each String[], concatenate all its elements to produce a single string. The concatenated versions of x, y and lengths contain single space separated lists of integers, where the i-th integers represent the x-coordinate and y-coordinate of the bottom left corner and side length, respectively, of the i-th square. The concatenated version of names contains a single space separated list of strings, where the i-th string represents the name of the i-th square.

Return a String[] containing exactly k elements - the names of the squares in the sequence. If there are multiple such sequences, return the one among them that comes first lexicographically. If there is no such sequence, return an empty String[].

 

Definition

    
Class:TheSquares
Method:findSequence
Parameters:String[], String[], String[], String[], int
Returns:String[]
Method signature:String[] findSequence(String[] x, String[] y, String[] lengths, String[] names, int k)
(be sure your method is public)
    
 

Notes

-Each square can be used only once in the resulting sequence.
-String[] A comes lexicographically before String[] B if the i-th element of A comes lexicographically before the i-th element of B and the j-th element of A is equal to the j-th element of B for all j less than i.
 

Constraints

-x, y, lengths and names will each contain between 1 and 50 elements, inclusive.
-Each element of x, y, lengths and names will contain between 1 and 50 characters, inclusive.
-x, y, lengths and names, when concatenated, will each contain a single space separated list of items without leading or trailing spaces, and each list will contain the same number of items.
-x, y and lengths, when concatenated, will each contain a single space separated list of integers, where each integer is between 1 and 1000, inclusive, with no leading zeroes.
-names, when concatenated, will contain a single space separated list of strings, where each string contains between 1 and 50 uppercase letters ('A'-'Z'), inclusive.
-k will be between 1 and 1000, inclusive.
 

Examples

0)
    
{"1 1 1 4 7 8 1000"}
{"1 1 1 4 7 8 1000"}
{"1 2 3 4 5 1 1000"}
{"X Y Z ALPHA BETA GAMMA DELTA"}
2
Returns: {"BETA", "GAMMA" }
There are several valid sequences of squares but (BETA, GAMMA) comes first lexicographically.
1)
    
{"1 1 1 4 7 8 1000"}
{"1 1 1 4 7 8 1000"}
{"1 2 3 4 5 1 1000"}
{"X Y Z ALPHA BETA GAMMA DELTA"}
3
Returns: {"Z", "Y", "X" }
Same example but with k = 3. This time there is no choice.
2)
    
{"4 4 4 4"}
{"7 7 7 7"}
{"47 47 47 47"}
{"GLUK GLUKA GLUKOVI GLUKOM"}
4
Returns: {"GLUK", "GLUKA", "GLUKOM", "GLUKOVI" }
Squares may coincide.
3)
    
{"1 15 27 39"}
{"3 13 22 36"}
{"8 3 5 974"}
{"ACB DEF GHI JKL"}
2
Returns: { }
There are no squares that lie inside other squares.
4)
    
{"123 453 754"}
{"119 487 874"}
{"1000 500 1"}
{"SQUARE SQUARE SQUARE"}
3
Returns: {"SQUARE", "SQUARE", "SQUARE" }
Names of squares are not necessarily distinct.
5)
    
{"3 5 10 1"}
{"5 8 10 1"}
{"974 990 1 1000"}
{"X Y X Y"}
3
Returns: {"Y", "X", "X" }
There are two pairs of squares with equal names.
6)
    
{"1 1 1 1"}
{"1 1 1 1"}
{"1 1 1 1"}
{"A A A A"}
1000
Returns: { }
The sequence John is looking for is too long.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheBestName

String Manipulation



Used in:

SRM 381

Used as:

Division II Level One

Writer:

Vasyl[alphacom]

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8413

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10804&pm=8413

Problem Statement

    

As some of you may know, there is no name better than JOHN. Let's define the rules for comparing names. Each letter has a weight ('A' - 1, 'B' - 2, ..., 'Z' - 26). The weight of a name is the sum of the weights of all its letters. For example, the name MARK has weight 13 + 1 + 18 + 11 = 43.

When comparing two names, the one with the larger weight is considered better. In case of a tie, the one that comes earlier lexicographically is better. But there is one exception - the name JOHN is the best name of all.

You are given a String[] names, each element of which contains a single name. Sort the names from best to worst and return the sorted String[].

 

Definition

    
Class:TheBestName
Method:sort
Parameters:String[]
Returns:String[]
Method signature:String[] sort(String[] names)
(be sure your method is public)
    
 

Constraints

-names will contain between 1 and 50 elements, inclusive.
-Each element of names will contain between 1 and 50 characters, inclusive.
-Each element of names will contain only uppercase letters ('A'-'Z').
 

Examples

0)
    
{"JOHN", "PETR", "ACRUSH"}
Returns: {"JOHN", "ACRUSH", "PETR" }
PETR has weight 59, ACRUSH has weight 70 and JOHN has a weight of only 47. But nevertheless JOHN is the best name, ACRUSH takes second place and PETR is the last.
1)
    
{"GLUK", "MARGARITKA"}
Returns: {"MARGARITKA", "GLUK" }
MARGARITKA is definitely better than GLUK.
2)
    
{"JOHN", "A", "AA", "AAA", "JOHN", "B", "BB", "BBB", "JOHN", "C", "CC", "CCC", "JOHN"}
Returns: 
{"JOHN",
"JOHN",
"JOHN",
"JOHN",
"CCC",
"BBB",
"CC",
"BB",
"AAA",
"C",
"AA",
"B",
"A" }
AA and B both have the same weight, but AA is better as it comes earlier lexicographically. For the same reason, AAA is better than C and BBB is better than CC.
3)
    
{"BATMAN", "SUPERMAN", "SPIDERMAN", "TERMINATOR"}
Returns: {"TERMINATOR", "SUPERMAN", "SPIDERMAN", "BATMAN" }
Here are some superheroes sorted by their names.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WarTransportation

Graph Theory



Used in:

SRM 462

Used as:

Division I Level Three

Writer:

stone

Testers:

PabloGilberto , Yarin , ivan_metelsky , zhuzeyuan

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8404

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=14147&pm=8404

Problem Statement

    

A country is at war, and one of its messenger soldiers must transport something of great importance from city 1 to city 2 using the highway system, which consists entirely of one-way highways. As soon as the soldier sets out on his mission, he is informed by an agent that the enemy has destroyed exactly one of the highways in the country. Unfortunately, it is unknown which highway was destroyed. He won't know which highway was destroyed until he arrives at the starting city of the destroyed highway. The soldier wants to use a strategy that will make the worst-case distance he has to travel as short as possible.

You are given an int n, the number of cities in the country. The cities are numbered 1 to n. The highways between cities are given in the String[] highways. Concatenate the elements of highways to get a comma separated list of integer triplets. Each triplet is formatted "a b c" (quotes for clarity), which means that there's a one-way highway of length c from city a to city b. Return the distance the messenger soldier will have to travel in the worst case. If there is a chance that he will never reach his destination, return -1 instead.

 

Definition

    
Class:WarTransportation
Method:messenger
Parameters:int, String[]
Returns:int
Method signature:int messenger(int n, String[] highways)
(be sure your method is public)
    
 

Notes

-Note that there may be multiple parallel highways from one city to another.
 

Constraints

-n will be between 2 and 100, inclusive.
-highways will contain between 1 and 50 elements, inclusive.
-Each element of highways will contain between 1 and 50 characters, inclusive.
-When concatenated, highways will contain a comma separated list of triplets of integers.
-Each integer triplet will be formatted "a b c" (quotes for clarity), where a and b are distinct integers between 1 and n, inclusive, and c is an integer between 1 and 1000, inclusive.
-Each integer in integer triplets will have no leading zeros and will contain only digits ('0'-'9').
 

Examples

0)
    
3
{"1 2 1,1 3 2,3 2 3"}
Returns: 5
The best strategy is to take the path 1->2 if the first highway is not destroyed. Otherwise, take the path 1->3->2.
1)
    
8
{"1 3 1,1 4 1,3 5 1,4 5 1,5 6 1,6 7 1,6 8 1,7 2 1,",
 "8 2 1"}
Returns: -1
If the highway from city 5 to city 6 is destroyed, the messenger can't finish the transportation.
2)
    
4
{"1 3 1,1 3 2,3 2 1,1 4 1,4 2 1"}
Returns: -1
No matter what strategy the messenger adopts, there is a chance that the transportation can't be finished.
3)
    
4
{"1 3 1,3 2 1,1 4 1,4 2 1,3 4 1"}
Returns: 3
The best strategy is to move to city 3 at first.
4)
    
20
{"1 13 3,13 4 7,4 3 4,3 10 8,10 18 9,18 12 6,12 2 3,",
 "1 17 6,17 13 6,13 9 4,9 10 8,10 7 2,7 5 5,5 19 9,1",
 "9 14 6,14 16 9,16 18 7,18 15 5,15 20 3,20 12 9,12 ",
 "8 4,8 11 3,11 4 1,4 3 7,3 2 3,20 10 2,1 18 2,16 19",
 " 9,4 15 9,13 15 6"}
Returns: 23

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GraphClique

Brute Force



Used in:

TCHS SRM 47

Used as:

Division I Level Two

Writer:

stone

Testers:

PabloGilberto , brett1479 , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8402

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10803&pm=8402

Problem Statement

    

You are given a String[] graphEdge representing an undirected graph.The j-th character of the i-th element of graphEdge is '1' (one) if there is an undirected edge between the i-th and j-th vertices, and '0' (zero) otherwise. Return a int[] containing the same number of elements as graphEdge, where the K-th (1-based) element is the number of different cliques of size K in the graph.

A clique is a non-empty set of vertices where every pair of vertices is directly connected by an edge in the graph. A clique of size K is a clique containing exactly K vertices.

 

Definition

    
Class:GraphClique
Method:allClique
Parameters:String[]
Returns:int[]
Method signature:int[] allClique(String[] graphEdge)
(be sure your method is public)
    
 

Constraints

-graphEdge will contain between 1 and 18 elements, inclusive.
-Each element of graphEdge will contain exactly N characters, where N is the number of elements in graphEdge.
-Each element of graphEdge will contain only the characters '0' (zero) and '1' (one).
-The j-th character of the i-th element of graphEdge will be equal to the i-th character of the j-th element of graphEdge.
-The i-th character of the i-th element of graphEdge will be '0' (zero).
 

Examples

0)
    
{"0"}
Returns: {1 }
A single vertex is also a clique of size 1.
1)
    
{"001","001","110"}
Returns: {3, 2, 0 }
Two cliques of size 2. One consists of vertices 0 and 2, and the other consists of vertices 1 and 2.
2)
    
{"0110","1001","1001","0110"}
Returns: {4, 4, 0, 0 }
3)
    
{"00110","00010","10000","11000","00000"}
Returns: {5, 3, 0, 0, 0 }
4)
    
{"00011","00100","01011","10101","10110"}
Returns: {5, 6, 2, 0, 0 }
5)
    
{"01111","10111","11011","11101","11110"}
Returns: {5, 10, 10, 5, 1 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Shape3D

Brute Force, Geometry



Used in:

SRM 414

Used as:

Division II Level Three

Writer:

StevieT

Testers:

PabloGilberto , Olexiy , gawry , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8394

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13505&pm=8394

Problem Statement

    

A shape in 3D Cartesian space is valid if it is made up of identical unit cubes, each cube in the shape has all its edges parallel to coordinate axes and its vertices are at non-negative integer coordinates. Two shapes are considered the same if one can be transformed into the other by some rotation and translation. You are given a description of a valid shape and should return the lexicographically smallest description of a valid shape that is the same as the one supplied.

You are given a String[] shape. Each element of shape describes a single unit cube from the shape and will contain three space-separated non-negative integers. The first of these gives the x-coordinate of the cube, the second gives the y-coordinate, and the third the z-coordinate. The cube is positioned such that the line segment between (x, y, z) and (x+1, y+1, z+1) is a diagonal of the cube and its edges are all parallel to the coordinate axes. Return a String[] containing the lexicographically smallest description of a valid shape in the same format as the input that can be transformed to the supplied shape by rotation and translation. Each element of your return must contain 3 single-space-separated non-negative integers without leading zeros and with no leading or trailing spaces. Each element of your return must describe a distinct cube from the shape.

 

Definition

    
Class:Shape3D
Method:findCanonical
Parameters:String[]
Returns:String[]
Method signature:String[] findCanonical(String[] shape)
(be sure your method is public)
    
 

Notes

-The lexicographically earlier of two String[]s is the one that has the lexicographically earlier String in the first position at which they differ.
-The lexicographically earlier of two Strings is the one that either has the earlier character (using ASCII ordering) at the first position at which they differ or is a proper prefix of the other.
-In ASCII ordering, a space character (' ') comes before any digit.
-The return will contain only digits ('0' - '9') and spaces (' ').
-Since the cubes of any valid shape must be aligned with the coordinate axes, any valid rotation can be achieved by a sequence of 90 degree rotations around the coordinate axes.
 

Constraints

-shape will contain between 1 and 50 elements, inclusive.
-Each element of shape will contain 3 space-separated integers without leading zeros between 0 and 1000, inclusive.
-Each element of shape will contain no leading or trailing spaces.
-The elements of shape will be distinct.
-The cubes described in shape will form a connected volume in 3D Cartesian space, where 2 cubes are considered to be connected if they share a face.
 

Examples

0)
    
{"0 0 0","1 0 0","1 1 0","1 1 1","1 0 1","0 1 1","0 0 1","0 1 0"} 
Returns: {"0 0 0", "0 0 1", "0 1 0", "0 1 1", "1 0 0", "1 0 1", "1 1 0", "1 1 1" }
This shape is a cube of side length 2, with a corner at the origin. No rotation or translation is required here, simply rearrange the order of the cubes to give the lexicographically minimum description.
1)
    
{"100 50 50","100 49 50","100 49 49"}
Returns: {"0 0 0", "0 0 1", "0 1 0" }
This shape needs to be rotated and translated so one of the squares lies at the origin.
2)
    
{"11 11 11","10 11 11","12 11 11"
,"11 11 10","11 11 12","11 10 11"
,"11 12 11","9 11 11","13 11 11"}
Returns: 
{"0 1 1",
"1 1 1",
"2 0 1",
"2 1 0",
"2 1 1",
"2 1 2",
"2 2 1",
"3 1 1",
"4 1 1" }
3)
    
{"100 900 800","101 900 800","102 900 800","102 899 800"
,"102 898 800","102 897 800","102 896 800","102 896 801"
,"102 896 802","102 896 803","102 896 804","102 896 805"
,"102 896 806","102 896 807","102 896 808"}
Returns: 
{"0 0 0",
"0 0 1",
"0 0 2",
"0 0 3",
"0 0 4",
"0 0 5",
"0 0 6",
"0 0 7",
"0 0 8",
"0 1 8",
"0 2 8",
"0 3 8",
"0 4 8",
"1 4 8",
"2 4 8" }
4)
    
{"2 2 0","2 2 1","2 2 3","2 2 4","2 0 2","2 1 2","2 3 2","2 4 2","0 2 2","1 2 2","3 2 2","4 2 2","2 2 2"}`
Returns: 
{"0 10 10",
"1 10 10",
"2 10 10",
"2 10 11",
"2 10 12",
"2 10 8",
"2 10 9",
"2 11 10",
"2 12 10",
"2 8 10",
"2 9 10",
"3 10 10",
"4 10 10" }
Be careful! Lexicographic ordering is not the same as numerical ordering.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PowerAdapters

Dynamic Programming, Graph Theory



Used in:

SRM 393

Used as:

Division II Level Three

Writer:

StevieT

Testers:

PabloGilberto , Olexiy , gawry , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8391

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11127&pm=8391

Problem Statement

    

Jane is about to go on a round-the-world trip. She is taking her laptop so she can compete in TopCoder competitions while she is away, but she is worred that she may not be able to charge the batteries. The power supply unit for her laptop has a plug suitable for the country that she lives in, but each country that she is visiting on her travels uses a different type of plug for their power outlets. Fortunately she can buy adapters to help her solve the problem. An adapter has a socket of one type, connected to a plug of another type, so she can plug the adapter into the power outlet, then plug her laptop into the adapter. Adapters can also be chained. For example, consider the case where her laptop has a US-style plug, and she has two adapters: one from a US socket to a European plug, and one from a European socket to a UK plug. She can plug her laptop into the first adapter, plug the first adapter into the second one, and then plug that into a UK power outlet to charge her laptop. She has already traveled widely, so might already own some adapters. What is the minimum number of additional adapters she will have to purchase in order to be able to charge her laptop in every country on her itinerary, assuming that she can buy an adapter from any country's socket to any other country's plug.

You are given a String[] adapters containing the details of the adapters that she already owns. Each element details a single adapter and is formatted "<socket> <plug>" (quotes for clarity), where <socket> and <plug> are both strings specifying country names. The adapter accepts a plug of type <socket>, and converts it to a plug of type <plug>. The names of the countries Jane is visiting are given in a String[] itinerary and her home country is given in the String homeCountry. Return the minimum number of additional adapters she needs to buy to be able to charge her computer in every country on her itinerary, given that her laptop plug is of type homeCountry.

 

Definition

    
Class:PowerAdapters
Method:needed
Parameters:String[], String[], String
Returns:int
Method signature:int needed(String[] adapters, String[] itinerary, String homeCountry)
(be sure your method is public)
    
 

Constraints

-adapters will contain between 0 and 50 elements, inclusive.
-Each element of adapters will contain between 3 and 50 characters, inclusive.
-Each element of adapters will be formatted "<socket> <plug>" (quotes for clarity), where <socket> and <plug> are non-empty Strings containing only uppercase letters ('A' - 'Z').
-In each element of adapters, <socket> and <plug> will be distinct.
-itinerary will contain between 1 and 16 elements, inclusive.
-Each element of itinerary will contain between 1 and 50 uppercase letters ('A' - 'Z'), inclusive.
-Each element of itinerary will be distinct.
-homeCountry will contain between 1 and 50 uppercase letters ('A' - 'Z'), inclusive.
 

Examples

0)
    
{"USA EUROPE","EUROPE UK"}
{"UK","EUROPE"}
"USA"
Returns: 0
The example from the problem statement. Jane is travelling to Europe and the UK and already has enough adapters to charge her laptop everywhere on her journey.
1)
    
{"USA CANADA","USA UK","GERMANY AUSTRALIA","GERMANY CANADA","AUSTRALIA USA","UK CANADA","JAPAN USA","JAPAN USA"}
{"AUSTRALIA","CANADA"}
"UK"
Returns: 1
2)
    
{"INDIA EGYPT","USA GERMANY","CHINA SPAIN","GERMANY NETHERLANDS","NETHERLANDS CHINA"}
{"CHINA","GERMANY","SPAIN"}
"NETHERLANDS"
Returns: 1
Jane already has an adapter for China and she can chain two together (Netherlands-China and China-Spain) to charge her laptop in Spain, so she only needs 1 additional adapter for Germany.
3)
    
{"AUSTRALIA GERMANY","CANADA INDIA","AUSTRALIA USA","USA INDIA","USA AUSTRALIA","CANADA GERMANY","USA AUSTRALIA","USA CANADA"}
{"AUSTRALIA","CANADA"}
"CANADA"
Returns: 1
Jane's home country can be on her itinerary.
4)
    
{"SPAIN AUSTRALIA","SPAIN NETHERLANDS","AUSTRALIA EGYPT"}
{"AUSTRALIA","EGYPT","NETHERLANDS"}
"UK"
Returns: 1
Jane needs to buy a UK-Spain adapter.
5)
    
{"CMCUG MEIACWT","CMCUG QLLUJCMB","MEIACWT UKINFV"
,"ODK QLLUJCMB","MEIACWT SXGBGF","CWW TUQ","YUAYI MEIACWT"
,"MEIACWT ODK","QLLUJCMB AGNAE","AGNAE GACPM","QLLUJCMB MAO"
,"KNCUTEW NNA","ODK MEIACWT","QJQUY ODK","AGNAE MEIACWT"}
{"AGNAE","ODK","TUQ","YUAYI"}
"AGNAE"
Returns: 2
6)
    
{"LALJ DMZEQ","ANKNMMUQ YINE","MAYNYVOM KQWCGASA"
,"YWEU DMZEQ","MAO YAE","CWNFS IAWGRCX","KQWCGASA CNUL"
,"CWNFS DMZEQ","QBHQCU EPMAKOI","CNUL KQWCGASA"
,"ANKNMMUQ YOXOQVO","YAE MAYNYVOM","IAWGRCX DMZEQ"}
{"CWNFS","DMZEQ","ISO","YOKKMK"}
"YINE"
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

HillWalker

Graph Theory



Used in:

SRM 383

Used as:

Division II Level Three

Writer:

StevieT

Testers:

PabloGilberto , legakis , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8383

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10806&pm=8383

Problem Statement

    

John is currently on a hillwalking holiday in a mountainous region. He really enjoys getting to high altitudes to enjoy the spectacular views of the region and he is planning a walk today that will get him to as high an altitude as possible. However, he also wants to be back at his hotel before it starts to get dark.



You are given a map of the region as a String[] landscape, describing a rectangluar section of the landscape. The altitude of the landscape at coordinates (j, i) is an integer represented by character j in element i of landscape, which will either be an uppercase letter ('A'-'Z') representing altitudes from 0 to 25, respectively, or a lowercase letter ('a'-'z'), representing altitudes from 26 to 51, respectively. John starts off at his hotel at coordinates (0, 0) and is planning to walk between points with integer coordinates. In each segment of his walk, he can walk to any orthogonally adjacent point, as long as the magnitude of the difference in altitude is no greater than threshold, otherwise the path is too steep. He cannot walk on a path that is too steep, regardless of whether he is walking uphill or downhill. If he walks from some point to another that is at equal or lower altitude (i.e., walking level or downhill) then the time it takes to walk between the points is 1. If he walks to a point at higher altitude (i.e., uphill) then the amount of time it takes is given by the difference in altitude between the points squared. For example, if he were to walk from a point with altitude 5 to one with altitude 9, then it would take (9 - 5) ^ 2 = 16 time units to walk that segment. If he were to walk the same segment, but in the opposite direction, it would only take him a single time unit.



Return an int containing the altitude of the highest point that he can reach on any walk that starts and finishes at (0, 0), given that the total time taken for the walk may not be greater than timeToDark.

 

Definition

    
Class:HillWalker
Method:highestPoint
Parameters:String[], int, int
Returns:int
Method signature:int highestPoint(String[] landscape, int threshold, int timeToDark)
(be sure your method is public)
    
 

Constraints

-landscape will contain between 1 and 25 elements, inclusive.
-Each element of landscape will contain between 1 and 25 characters, inclusive.
-Each element of landscape will contain the same number of characters.
-Each character in landscape will be either a lowercase letter ('a'-'z') or an uppercase letter ('A'-'Z').
-threshold will be between 1 and 52, inclusive.
-timeToDark will be between 1 and 1,000,000, inclusive.
 

Examples

0)
    
{"AD"
,"JG"}
3
10000
Returns: 9
John has plenty of time until it gets dark, so he can get to the highest point. He can't move directly to the highest point, even though it is adjacent to his hotel, because the slope is too steep, but he can take a longer path which is less steep and he returns on the same path.
1)
    
{"AD"
,"JG"}
3
29
Returns: 6
This is the same map, but he now doesn't quite have enough time to make it to the top. Note that he cannot walk down a slope that is too steep, so he could not move directly from the highest point back to his hotel.
2)
    
{"AABCDE"
,"GJIHGF"
,"MKLMNO"
,"STSRQP"
,"YUVWXY"
,"edcbaZ"}
6
36
Returns: 30
This is the height map shown in the figure below. He has just enough time to make it to the top, but he has to follow a winding path. Otherwise he would run out of time.



3)
    
{"BCDE"
,"AJKF"
,"AIHG"
,"AAAA"
,"AOMK"
,"AQSI"
,"ACEG"}
5
14
Returns: 10
This map has 2 separate mountains, as shown in the figure below. John doesn't have much time today, so he gets highest if he climbs the smaller one.



4)
    
{"BCDE"
,"AJKF"
,"AIHG"
,"AAAA"
,"AOMK"
,"AQSI"
,"ACEG"}
5
57
Returns: 18
This is the same map, but he has more time for his walk in this case. He can therefore climb right to the top of the higher mountain.
5)
    
{"ABCDEFK"}
3
1000
Returns: 5
The highest point is unreachable in this case.
6)
    
{"TRRVUXefk"
,"bSNMOWcff"
,"bRPNNQZip"
,"XSRUTVcfj"
,"WbZQPXZbV"
,"XdYSRWVOP"
,"feedVVcZR"
,"XhfdZZefg"}
4
50
Returns: 28

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SyllableSorting

Sorting



Used in:

SRM 374

Used as:

Division I Level One , Division II Level Two

Writer:

jbernadas

Testers:

PabloGilberto , Olexiy , Andrew_Lazarev

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8374

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10793&pm=8374

Problem Statement

    

Syllable sorting is a method of sorting words based on their syllabic decompositions. The first step is to decompose each word into syllables. A syllable is defined as a maximal non-empty substring of consonants followed by a maximal non-empty substring of vowels. The only vowels are 'a', 'e', 'i', 'o' and 'u'. All other letters are considered consonants. All words will start with a consonant and end with a vowel.



To compare two words syllabically, first decompose them into sequences of syllables. For example, the words "zcdbadaerfe" and "foubsyudba" decompose as follows:

  • "zcdbadaerfe" = {"zcdba", "dae", "rfe"}
  • "foubsyudba" = {"fou", "bsyu", "dba"}

Then, sort each sequence of syllables alphabetically. In the above example, the sequences become:

  • {"dae", "rfe", "zcdba"}
  • {"bsyu", "dba", "fou"}

Then, compare these sorted sequences lexicographically. A sequence S1 comes before a sequence S2 lexicographically if S1 has an alphabetically earlier element at the first index at which they differ. In the above example, the second sequence comes earlier lexicographically because "bsyu" comes before "dae" alphabetically.



If two sorted sequences are equal, then compare their corresponding unsorted sequences instead. For example, the words "daba" and "bada" decompose into the same sorted sequence {"ba", "da"}. Compare the unsorted sequences {"da", "ba"} and {"ba", "da"} to determine that "bada" comes before "daba".



You are given a String[] words. Sort the words using the method above and return the resulting String[].



 

Definition

    
Class:SyllableSorting
Method:sortWords
Parameters:String[]
Returns:String[]
Method signature:String[] sortWords(String[] words)
(be sure your method is public)
    
 

Constraints

-words will contain between 1 and 50 elements, inclusive.
-Each element of words will contain between 2 and 50 characters, inclusive.
-Each element of words will contain only lowercase letters ('a'-'z').
-The first character of each element of words will be a consonant.
-The last character of each element of words will be a vowel.
 

Examples

0)
    
{"xiaoxiao", "yamagawa", "gawayama"}
Returns: {"gawayama", "yamagawa", "xiaoxiao" }

After decomposing the words into sequences of syllables, we get the following unsorted and sorted sequences of syllables:

   WORD    |    UNSORTED SEQUENCES    |     SORTED SEQUENCES
-----------+--------------------------+--------------------------
"xiaoxiao" | {"xiao", "xiao"}         | {"xiao", "xiao"}
"yamagawa" | {"ya", "ma", "ga", "wa"} | {"ga", "ma", "ya", "wa"}
"gawayama" | {"ga", "wa", "ya", "ma"} | {"ga", "ma", "ya", "wa"}

To compare "xiaoxiao" with the other two words, we use the sorted sequences of syllables. However, to compare "yamagawa" with "gawayama" we have to use the unsorted sequences because the sorted ones are equal.

1)
    
{"bcedba", "dbabce", "zyuxxo"}
Returns: {"bcedba", "dbabce", "zyuxxo" }
2)
    
{"hgnibqqaxeiuteuuvksi", "jxbuzui", "zrotyqeruiydozui",
 "ywuuzkto", "lmopbookoagyco", "vredfvavvexliu"}
Returns: 
{"hgnibqqaxeiuteuuvksi",
"vredfvavvexliu",
"lmopbookoagyco",
"jxbuzui",
"zrotyqeruiydozui",
"ywuuzkto" }
3)
    
{"crazgo", "cwsoygiokiuo", "yueoseeu", "tuadiojvugeoe",
 "naumxditui", "sgukkelyoi", "nrohjuasoia", "mgabmo"}
Returns: 
{"mgabmo",
"crazgo",
"cwsoygiokiuo",
"tuadiojvugeoe",
"nrohjuasoia",
"sgukkelyoi",
"naumxditui",
"yueoseeu" }
4)
    
{"wheewjuguoi", "coutcu", "hqivaa", "sgiibgwi", "ypaqpki",
 "bgyikouapae", "wqakeu", "skolfo", "pzesaa", "ypivhi"}
Returns: 
{"sgiibgwi",
"bgyikouapae",
"coutcu",
"wheewjuguoi",
"hqivaa",
"wqakeu",
"skolfo",
"pzesaa",
"ypaqpki",
"ypivhi" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CollectingRiders

Graph Theory



Used in:

SRM 382

Used as:

Division I Level One , Division II Level Two

Writer:

dkorduban

Testers:

PabloGilberto , Olexiy , marek.cygan , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8319

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10805&pm=8319

Problem Statement

    

A rider is a fantasy chess piece that can jump like a knight several times in a single move. (See notes for a description of how a knight jumps.) A rider that can perform a maximum of K jumps during a single move is denoted as a K-rider. For example, a 2-rider can jump once or twice during a single move, and a 1-rider is a traditional knight.



There are some riders of different types on a chessboard. You are given a String[] board representing the layout of the pieces. The j-th character of the i-th element of board is the content of the square at row i, column j. If the character is a digit K between '1' and '9', the square contains a K-rider. Otherwise, if the character is a '.', the square is empty. Return the minimal total number of moves necessary to move all the riders to the same square. Only one piece can move during each move. Multiple riders can share the same squares at all times during the process. Return -1 if it is impossible.

 

Definition

    
Class:CollectingRiders
Method:minimalMoves
Parameters:String[]
Returns:int
Method signature:int minimalMoves(String[] board)
(be sure your method is public)
    
 

Notes

-A traditional knight has up to 8 moves from a square with coordinates (x,y) to squares (x+1,y+2), (x+1,y-2), (x+2,y+1), (x+2,y-1), (x-1,y+2), (x-1,y-2), (x-2,y+1), (x-2,y-1), and can not move outside the chessboard.
 

Constraints

-board will contain between 1 and 10 elements, inclusive.
-Each element of board will contain between 1 and 10 characters, inclusive.
-All elements of board will have the same length.
-board will contain only positive digits ('1'-'9') and '.' characters.
-board will contain at least one digit.
 

Examples

0)
    
{"...1",
 "....",
 "2..."}
Returns: 2
The 2-rider can jump from (2,0) to (0,1) in the first move, and then from (0,1) to (2,2) to (0,3) in the second.
1)
    
{"........",
 ".1......",
 "........",
 "....3...",
 "........",
 "........",
 ".7......",
 "........"}
Returns: 2
In 2 moves, we can move all the pieces to the cell initially occupied by the 1-rider.
2)
    
{"..",
 "2.",
 ".."}
Returns: 0
No moves are necessary.
3)
    
{".1....1."}
Returns: -1
4)
    
{"9133632343",
 "5286698232",
 "8329333369",
 "5425579782",
 "4465864375",
 "8192124686",
 "3191624314",
 "5198496853",
 "1638163997",
 "6457337215"}
Returns: 121
Kind of maximal test.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DukeOnLargeChessBoard

Greedy



Used in:

SRM 375

Used as:

Division I Level Three

Writer:

darnley

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8317

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10794&pm=8317

Problem Statement

    

Let's define a duke as a chess figure that is only allowed to move 1 cell up, down, left or right.

Let's consider a large chess board of size 1000000×1000000. Both rows and columns are numbered from "000000" to "999999". A cell is labeled as "(<Column number>, <Row number>)" (quotes for clarity), where <Column number> and <Row number> each contain exactly six digits. For example, "(499999, 000000)" and "(500000, 000000)" are the two cells in the middle of the bottom row.

A duke is placed on a chessboard in the cell initPosition.

Let's describe a duke's path as a space-separated list of cells visited by the duke. For example, "(444444, 600000) (444445, 600000) (444445, 599999)" is a path consisting of two moves. The first move is one cell to the right and the second move is one cell down.

A path is called simple if it contains no repeated cells.

Consider the lexicographically greatest simple path of a duke starting in initPosition. Return the last cell of this path in the same format as initPosition.

 

Definition

    
Class:DukeOnLargeChessBoard
Method:lastCell
Parameters:String
Returns:String
Method signature:String lastCell(String initPosition)
(be sure your method is public)
    
 

Notes

-A String A is greater than a String B lexicographically if B is a proper prefix of A, or if A has a greater character at the first position where the strings differ.
 

Constraints

-initPosition will contain exactly 16 characters.
-initPosition will be a valid notation of a cell inside the board.
 

Examples

0)
    
"(999999, 999999)"
Returns: "(000000, 999999)"
The duke is located in the upper right corner. First he goes all the way down to (999999, 000000). Then he has to move one cell left and then goes all the way up. Again, one move left and all the way down. This snake-like pattern covers the entire board and finishes in the left-most row, where the duke moves up until he stops in the upper-left corner of the board, which is (000000, 999999).
1)
    
"(999999, 000000)"
Returns: "(000000, 000000)"
If a duke starts in the lower-right corner of the board, he will also follow a snake-like pattern. This time, he takes odd columns up and even columns down. In the end he will move down the 000000 column and finish his path in (000000, 000000).
2)
    
"(000000, 999998)"
Returns: "(000000, 999999)"
The duke will visit only 2000000 cells on his path if he starts from this point. First he will move all the way right to (999999, 999998), then one cell up to (999999, 999999) and all the way left to (000000, 999999). In this cell we will have no unvisited neighbors to move into.
3)
    
"(999998, 000001)"
Returns: "(999999, 000000)"
4)
    
"(123456, 235711)"
Returns: "(000000, 112256)"
5)
    
"(987654, 123456)"
Returns: "(864197, 000000)"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TwistyPassages

Graph Theory



Used in:

SRM 378

Used as:

Division I Level Three

Writer:

bmerry

Testers:

PabloGilberto , Olexiy , marek.cygan , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8282

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10798&pm=8282

Problem Statement

    

You find yourself in a maze of twisty little passages, all alike. Each passage connects two rooms, and can be traveled in either direction. The rooms are all circular and look exactly the same, and the entrances to the passages are evenly spaced around the room, making it impossible to know anything except the number of passages connected to the room. Rooms with the same number of connecting passages are said to have the same type. The passages are so twisty that by the time you reach the other end of one, you have no idea where you are or which direction you are facing.

You have a map of the maze, but you have no idea where you are. "No problem," you think, "I'll walk around the maze and deduce where I started." Suppose that you follow some path, and note the type of each room you pass through and your decisions about which passages you selected (relative to the passage you entered by). You can then trace the same route on your map for every possible starting room and orientation of that room, and see if the room types match up. You hope that by choosing the right path, you can eliminate all but one possible starting room.

After thinking about the problem some more, you realize that some sets of rooms cannot be told apart. That is, if you started in one of them, this method would never be able to tell you which one regardless of the path you chose.

You will be given a String[] maze, describing the maze. Element i of maze is a space-separated list of numbers, which are the numbers of the rooms connected to room i by passages. The numbers are listed in the order that they appear going clockwise around the room from an arbitrary starting point. Return a int[] containing the same number of elements as maze, where element i of this list is the number of other rooms that cannot be told apart from room i.

 

Definition

    
Class:TwistyPassages
Method:similarRooms
Parameters:String[]
Returns:int[]
Method signature:int[] similarRooms(String[] maze)
(be sure your method is public)
    
 

Constraints

-maze will contain exactly N elements, where N is between 1 and 50, inclusive.
-Each element of maze will contain between 0 and 50 characters, inclusive.
-Each element of maze will be a space-separated list of integers, with no leading, trailing, or double spaces.
-Each integer in maze will be between 0 and N - 1, inclusive, with no extra leading zeroes.
-For all i between 0 and N - 1 inclusive, element i of maze will not contain i.
-For all i and j between 0 and N - 1 inclusive, element i of maze will contain at most one j.
-For all i and j between 0 and N - 1 inclusive, element i of maze will contain j if and only if element j of maze contains i.
 

Examples

0)
    
{"1 2 3", "0", "0", "0"}
Returns: {0, 2, 2, 2 }
A central room with three passages leading to three dead ends. The dead ends can not be told apart.
1)
    
{"1 2 3", "0", "0", "0 4", "3"}
Returns: {0, 0, 0, 0, 0 }
Now we add a passage to one of the dead ends. When in room 0, going down each passage will show which one is room 3 (it is the only one with 2 passages), which gives the orientation of room 0. If you started in some other room, proceed to room 0, determine its orientation, and then you will know where you started.
2)
    
{"1 2 3", "0", "0", "0 4", "3",
 "6 7 8", "5", "5", "5 9", "8"}
Returns: {1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
Two disconnected copies of the previous example. It is impossible to tell corresponding rooms apart.
3)
    
{"1 2 3 4",  "0", "0 5",  "0", "6 0",  "2", "4",
"8 10 9 11", "7", "7 12", "7", "13 7", "9", "11"}
Returns: {0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }
The two components are similar, but the order of passages around the central chamber is different and so they can be told apart.
4)
    
{"1 2", "2 0", "0 1", "4 6", "5 3", "6 4", "3 5"}
Returns: {6, 6, 6, 6, 6, 6, 6 }
A triangle and a square. Since you cannot tell when you get back to your initial room, there is no way to tell which component you are in.
5)
    
{"1 2 3", "4 5 0", "6 7 0", "8 9 0", "10 11 1", "12 13 1", 
 "14 15 2", "16 17 2", "18 19 3", "20 21 3", "22 23 4", 
 "24 25 4", "26 27 5", "28 29 5", "30 31 6", "32 33 6", 
 "34 35 7", "36 37 7", "38 39 8", "40 41 8", "42 43 9", 
 "44 45 9", "10", "10", "11", "11", "12", "12", "13", "13",
 "14", "14", "15", "15", "16", "16", "17", "17", "18", "18",
 "19", "19", "20", "20", "21", "21"}
Returns: 
{0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DukeOnChessBoard

Greedy, Search



Used in:

SRM 375

Used as:

Division II Level Two

Writer:

darnley

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8268

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10794&pm=8268

Problem Statement

    

Let's define a duke as a chess figure that is only allowed to move 1 cell up, down, left or right.

A duke is placed on an n×n board in the cell initPosition. In this problem, columns are marked 'a', 'b', etc. from left to right, and rows are marked '1', '2', etc. from bottom to top. Cells are notated as "cr" (quotes for clarity), where c is the column and r is the row.

Let's describe a duke's path as a dash-separated list of cells visited by the duke. For example, "c5-b5-b4" is a path consisting of two moves. The first move is one cell to the left (from c5 to b5), and the second is one cell down (from b5 to b4).

A path is called simple if it contains no repeated cells.

Return the lexicographically greatest simple path of a duke starting in initPosition. If the length of the path exceeds 40 characters, return only the first 20 and the last 20 characters, separated by three dots. (See Example #1).

 

Definition

    
Class:DukeOnChessBoard
Method:dukePath
Parameters:int, String
Returns:String
Method signature:String dukePath(int n, String initPosition)
(be sure your method is public)
    
 

Notes

-A String A is greater than a String B lexicographically if B is a proper prefix of A, or if A has a greater character at the first position where the strings differ.
 

Constraints

-n will be between 2 and 8, inclusive.
-initPosition will contain exactly 2 characters.
-The first character of initPosition will be a lowercase letter between 'a' and 'h', inclusive.
-The second character of initPosition will be a digit between '1' and '8', inclusive.
-initPosition will denote a cell inside the n×n board.
 

Examples

0)
    
3
"b2"
Returns: "b2-c2-c3-b3-a3-a2-a1-b1-c1"
After the first move to the right, the duke will traverse the perimeter of the board in the counterclockwise direction.
1)
    
4
"d4"
Returns: "d4-d3-d2-d1-c1-c2-c3...b3-b2-b1-a1-a2-a3-a4"
The duke will move down three times, then left, then up three times and left, in a snake-like fashion. The lexicographically greatest path is 47 characters long, so its middle part is replaced by "...".
2)
    
3
"a2"
Returns: "a2-b2-c2-c3-b3-a3"
3)
    
4
"d3"
Returns: "d3-d4-c4-c3-c2-d2-d1...b2-b3-b4-a4-a3-a2-a1"
4)
    
8
"a8"
Returns: "a8-b8-c8-d8-e8-f8-g8...a1-a2-a3-a4-a5-a6-a7"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DateFieldCorrection

Graph Theory, Simple Search, Iteration



Used in:

SRM 375

Used as:

Division I Level Two

Writer:

darnley

Testers:

PabloGilberto , Olexiy , ivan_metelsky , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8267

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10794&pm=8267

Problem Statement

    

An application you're working on contains an input text field where a user types in a date.

The user is instructed to type in a date in the form "<Month> <Day>" (quotes for clarity), where <Month> is the English name of the month ("January", "February", etc.) and <Day> is the day of the month, without leading zeroes.

However, a user can make errors when typing. The following model is suggested: the user always presses the correct number of keys, but he or she can mistype one key for another. Let's define the penalty for a typing error as the length of the shortest path between the key that was actually pressed and the intended key in the graph shown below.

Here red lines denote edges of length 1 and green lines denote edges of length 3. When calculating the penalty, the cases of the letters are ignored.

Obviously, the penalty for typing a correct key is 0. Now, define the distance between the input of the user and a correct date of the same length as the sum of the penalties for mistyping over all corresponding characters.

For example, distance("TopCoder", "March 31") = penalty("T", "M") + penalty("O", "A") + ... + penalty("R", "1") = 4 + 8 + 6 + 0 + 3 + 4 + 1 + 4 = 30

Given a String input, return a correct date (in the format described above) that has the smallest distance from the input. In case of a tie, return the date that is earlier in the year.

 

Definition

    
Class:DateFieldCorrection
Method:correctDate
Parameters:String
Returns:String
Method signature:String correctDate(String input)
(be sure your method is public)
    
 

Notes

-Consider February 29 a valid date (as it is in leap years).
-The names of the months are "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November" and "December".
-The lengths of the corresponding months are 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30 and 31 days.
 

Constraints

-input will contain between 5 and 12 characters, inclusive.
-input will contain only uppercase and lowercase letters ('A'-'Z', 'a'-'z'), digits ('0'-'9') and spaces (' ').
 

Examples

0)
    
"Novebmer 10"
Returns: "November 10"
Swapping "b" and "m" is just a little typo and should be corrected easily.
1)
    
"September 15"
Returns: "September 15"
A date that is typed in correctly shouldn't be changed at all.
2)
    
"Juny 4"
Returns: "June 4"
"Juny" could stand both for "June" and "July". The penalty for mistyping is 3 in each case. If that's the case, June is preferred because it is earlier than July.
3)
    
"Juny 31"
Returns: "July 31"
Once again, both June and July could have been meant by the user. However, if it's June then there is at least one typo in the day (there is no 31th day in June).
4)
    
"TopCoder"
Returns: "April 24"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

OddGraph

Advanced Math, Graph Theory



Used in:

TCCC07 Semi 3

Used as:

Division I Level Two

Writer:

dgoodman

Testers:

PabloGilberto , Yarin , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8266

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10958&pm=8266

Problem Statement

    We want to design a network consisting of n identical Worker nodes and one Server node. The network must be connected and must not contain any cycles. We also require that each Worker node must be connected to an odd number of other nodes. How many distinct networks are there?

Here is a listing of all the distinct networks containing exactly 5 worker nodes:

                                                       
       W               W     W              W          W  W 
       |                \    |              |          | /   
   W---S----W            S---W          S---W      S---W    
       | \              /    |              |          | \  
       W  W            W     W          W---W---W      W  W  
                                                       
Two configurations G and G' are not distinct if there is a 1-1 mapping between their nodes such that the server in G maps to the server in G', and such that for every pair of nodes in G the pair that they are mapped to in G' is connected if and only if the pair in G is connected. Note that two configurations are not distinct if they have the same connection pattern, even if they are different geometrically as displayed in the plane. For example, these two configurations with 8 worker nodes are not distinct:

   W   W   W          W       W                                      
   |   |   |          |       |  
   W---S---W      W---S-------W                                                 
   |   |   |          |       | 
   W   W   W      W---W---W   W          
Given n, return the number of distinct networks that can be constructed with exactly n worker nodes.
 

Definition

    
Class:OddGraph
Method:count
Parameters:int
Returns:int
Method signature:int count(int n)
(be sure your method is public)
    
 

Notes

-The answer will fit in an int.
 

Constraints

-n will be between 1 and 40, inclusive.
 

Examples

0)
    
5
Returns: 4
The 4 networks are listed above.
1)
    
1
Returns: 1
S---W is the only network with 1 worker node.
2)
    
40
Returns: 929556155

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CardsAndSlots

Search



Used in:

TCCC07 Semi 1

Used as:

Division I Level One

Writer:

andrewzta

Testers:

PabloGilberto , Olexiy , Jan_Kuipers , misof , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8256

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10956&pm=8256

Problem Statement

    

You have n cards. Each card has some integer value, and some letter written on it. You also have n slots in a row. Each slot has some required value.

You must place the cards in the slots such that each slot contains a card with a value greater than or equal to the required value of that slot. You must order the cards such that the string formed by reading the letters on the cards from left to right comes as early as possible lexicographically while not violating the first rule.

You are given a int[] values and a String letters, the i-th elements of which are the value and letter, respectively, of the i-th card. You are also given a int[] required, the i-th element of which is the required value of the i-th slot. The slots are ordered from left to right. Place the cards into the slots as described above and return the resulting string. If there is no valid way to fill the slots, return an empty string instead.

 

Definition

    
Class:CardsAndSlots
Method:firstValid
Parameters:int[], String, int[]
Returns:String
Method signature:String firstValid(int[] values, String letters, int[] required)
(be sure your method is public)
    
 

Constraints

-values will contain between 1 and 50 elements, inclusive.
-Each element of values will be between 1 and 1000, inclusive.
-letters will contain exactly n characters, where n is the number of elements in values.
-letters will contain only uppercase letters ('A'-'Z').
-required will contain the same number of elements as values.
-Each element of required will be between 1 and 1000, inclusive.
 

Examples

0)
    
{1, 2, 3}
"ABC"
{2, 2, 1}
Returns: "BCA"
1)
    
{1, 2, 3, 4, 5}
"BBBAA"
{1, 1, 1, 1, 5}
Returns: "ABBBA"
Note that there can be equal letters on different cards.
2)
    
{1, 1}
"AA"
{2, 2}
Returns: ""
No card fits any slot.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Polygon

Geometry, Search



Used in:

TCCC07 Wildcard

Used as:

Division I Level Three

Writer:

andrewzta

Testers:

PabloGilberto , Olexiy , Jan_Kuipers , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8254

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10979&pm=8254

Problem Statement

    

You are given a polygon (possibly non-convex) with edges parallel to the coordinate axes. The polygon is non-self-intersecting, meaning that no two of its edges share any common points, with the exception of vertices, each of which is shared between exactly two adjacent edges.

Consider all points with integer coordinates inside the polygon (including the points on its border). Sort all of them lexicographically (first, by x-coordinate, then by y-coordinate). You will be asked to return the coordinates of some points in this list.

You are given int[]s x and y, the i-th elements of which are the x and y coordinates, respectively, of the i-th vertex of the polygon in a counterclockwise traversal. You are also given a String[] k, each element of which is the index of a point in the sorted list. Return a String[], the i-th element of which is the k[i]-th point with integer coordinates inside the polygon (1-based). Format each returned element as "x-coordinate y-coordinate" (quotes for clarity only, separate x and y coordinates with one space). For each i, if there are less than k[i] points, the corresponding element in the return value must be an empty String.

 

Definition

    
Class:Polygon
Method:getKthPoint
Parameters:int[], int[], String[]
Returns:String[]
Method signature:String[] getKthPoint(int[] x, int[] y, String[] k)
(be sure your method is public)
    
 

Constraints

-x will contain between 4 and 50 elements, inclusive.
-y will contain the same number of elements as x.
-Each element of x will be between 0 and 10^9, inclusive.
-Each element of y will be between 0 and 10^9, inclusive.
-x and y will describe a counterclockwise traversal of vertices in a polygon.
-The polygon described by x and y will have edges parallel to coordinate axes.
-The polygon described by x and y will be non-self-intersecting.
-All vertices of the polygon will be distinct.
-k will contain between 1 and 50 elements, inclusive.
-Each element of k will be an integer between 1 and 10^18, inclusive, with no leading zeroes.
 

Examples

0)
    
{0, 2, 2, 0}
{0, 0, 2, 2}
{"1", "2", "3", "4", "5", "6", "7", "8", "9"}
Returns: {"0 0", "0 1", "0 2", "1 0", "1 1", "1 2", "2 0", "2 1", "2 2" }
These are all points that belong to a 2x2 square.
1)
    
{0,1,2,2,0}
{0,0,0,1,1}
{"1","6","2","3","5","4","7"}
Returns: {"0 0", "2 1", "0 1", "1 0", "2 0", "1 1", "" }
Note that there can be two consecutive parallel edges. Also note that k need not be sorted.
2)
    
{0, 5, 5, 3, 3, 4, 4, 3, 3, 0, 0, 1, 1, 0}
{0, 0, 1, 1, 2, 2, 5, 5, 4, 4, 3, 3, 1, 1}
{"1","4","6","7","12","15","20","25","28","29"}
Returns: {"0 0", "0 4", "1 1", "1 2", "2 2", "3 0", "3 5", "4 4", "5 1", "" }
3)
    
{0,0,1,1}
{1,0,0,1}
{"1","2","3","4"}
Returns: {"0 0", "0 1", "1 0", "1 1" }
Note that the first edge can be vertical.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Police

Graph Theory, Greedy



Used in:

TCCC07 Semi 3

Used as:

Division I Level One

Writer:

andrewzta

Testers:

PabloGilberto , vorthys , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8253

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10958&pm=8253

Problem Statement

    

There are n junctions in the city, some of them are connected by one-way roads. The mayor of the city would like to build police stations at some junctions to fight crime in the city. Building a police station at junction i costs cost[i].

The police station at junction i is said to control junction j if it is possible for the police patrol to drive from junction i to junction j and back. Each junction must be controlled by some police station.

You are given int[] cost and String[] roads. The j-th character of the i-th element of roads is 'Y' if there is a one-way road from junction i to junction j, or 'N' of there is none. Return the minimal total cost to build the police stations.

 

Definition

    
Class:Police
Method:minimalCost
Parameters:int[], String[]
Returns:int
Method signature:int minimalCost(int[] cost, String[] roads)
(be sure your method is public)
    
 

Constraints

-cost will contain between 1 and 50 elements, inclusive.
-Each element of cost will be between 1 and 10^6, inclusive.
-roads will contain the same number of elements as cost.
-Each element of roads will contain n characters, where n is the number of elements of roads.
-Each element of roads will contain only characters 'Y' and 'N'.
-For all i the element i of roads[i] will be 'N'.
 

Examples

0)
    
{1, 2, 3, 4, 5}
{"NNNYY", "YNNNN", "NNNYN", "NNYNN", "NYNNN"}
Returns: 4
You can build police stations in cities 1 and 3.
1)
    
{1000000,1000000}
{"NY", "YN"}
Returns: 1000000
It is enough to build one station.
2)
    
{5, 3, 10, 4}
{"NYNN", "NNYN", "NNNY", "YNNN"}
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DriveCar

Dynamic Programming, Graph Theory



Used in:

TCHS SRM 44

Used as:

Division I Level Two

Writer:

boba5551

Testers:

PabloGilberto , brett1479 , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8250

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10795&pm=8250

Problem Statement

    

Little John likes to play driving games. One of his favorite games involves a horizontal three-lane road divided into cells. The cells are numbered 0, 1, 2, etc. from left to right, and the lanes are numbered 0, 1, 2 from top to bottom. The car is initially located in the middle lane in the leftmost cell (lane 1, cell 0). The goal of the game is to reach any lane of the rightmost cell without hitting any obstacles or leaving the road.

The car moves horizontally one cell at a time. Each time it moves to the next cell, it can either stay in the same lane or move diagonally to an adjacent lane. More formally, if the car is in lane i, cell j, then after the next move, it can be in one of the following lanes of cell j+1: i, i-1 (only if i>0), or i+1 (only if i<2).

The road is given as a String[] road, where the j-th character of the i-th element is the content of lane i, cell j. '.' represents open road and '#' represents an obstacle. The car hits an obstacle if it ends a move on a '#' character. Return the fewest number of lane changes necessary to reach the rightmost cell without hitting any obstacles or leaving the road. If it is impossible to reach the rightmost cell, return -1 instead.

 

Definition

    
Class:DriveCar
Method:minNumberOfDrifts
Parameters:String[]
Returns:int
Method signature:int minNumberOfDrifts(String[] road)
(be sure your method is public)
    
 

Constraints

-road will contain exactly 3 elements.
-All elements of road will contain the same number of characters.
-Each element of road will contain between 1 and 50 characters, inclusive.
-Each character in each element of road will be '.' or '#'.
-The leftmost character of element 1 of road will be '.'.
 

Examples

0)
    
{"....",
 "....",
 "...."}
Returns: 0
John doesn't need to change lanes to win the game:
       ....      ....      ....      ....
start  C...  ->  .C..  ->  ..C.  ->  ...C
       ....      ....      ....      ....
1)
    
{"#.###.##",
 ".#.#.#.#",
 "###.###."}
Returns: 7
#.###.##    #C###.##    #.###.##    #.###.##    #.###.##    #.###C##    #.###.##    #.###.##
C#.#.#.# -> .#.#.#.# -> .#C#.#.# -> .#.#.#.# -> .#.#C#.# -> .#.#.#.# -> .#.#.#C# -> .#.#.#.#
###.###.    ###.###.    ###.###.    ###C###.    ###.###.    ###.###.    ###.###.    ###.###C -> end
2)
    
{"..#....#..#.#...#..",
 "...#.#...#.#..#..#.",
 ".##..........#...#."}
Returns: 5
3)
    
{"#..#.#.##.",
 ".#.#...##.",
 ".###.##.#."}
Returns: -1
John can't reach the end of the road.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PolylineUnion

Brute Force, Geometry



Used in:

SRM 368

Used as:

Division I Level Two

Writer:

misof

Testers:

PabloGilberto , vorthys , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8249

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10936&pm=8249

Problem Statement

    

A polyline is a sequence of line segments such that each segment starts at the point where the previous segment ended.

If two polylines have a common point, we say that they belong to the same picture. The common point does not have to be an endpoint of a line segment.

Your method will be given a String[] polylines. Concatenate the elements of polylines to get a space-separated list of polyline descriptions. Each polyline description consists of one or more point descriptions, separated by single dashes ('-'). Each point is described by its two non-negative integer coordinates, separated by a comma (',').

Return the number of pictures in the union of all the given polylines.

 

Definition

    
Class:PolylineUnion
Method:countComponents
Parameters:String[]
Returns:int
Method signature:int countComponents(String[] polylines)
(be sure your method is public)
    
 

Notes

-The point sequence that defines a polyline may contain the same point more than once, and even consecutive points are allowed to be equal.
-A polyline may be just a single point.
 

Constraints

-polylines will have the format described in the problem statement.
-polylines will contain between 1 and 50 elements, inclusive.
-Each of the elements in polylines will contain between 0 and 50 characters, inclusive.
-Each coordinate of each point specified in polylines will be between 0 and 10000, inclusive.
-The point coordinates in polylines will not contain unnecessary leading zeros.
 

Examples

0)
    
{"0,0-10,10 0,10-10,0"}
Returns: 1

Two intersecting line segments form a single picture.

1)
    
{"0,0-10,5 5,0-15,5-10,10-5,5"}
Returns: 2

Two non-intersecting polylines.

2)
    
{"1","3,0-5,5 4,0-4,20"}
Returns: 2
Note that you first have to concatenate the elements of polylines and only then parse the resulting string.
3)
    
{"10,0-10,1-9,2-9,3-8,4 ","8,2-9,2-10,3 ","12,2-11,2-9,1"}
Returns: 1

Together, these three polylines form a single picture. From a graph theoretical point of view, this picture can be seen as a tree with 11 vertices. (Ten of them are the given points and one is the intersection of 10,1-9,2 and 11,2-9,1.)

4)
    
{"0,0-10,0-0,0 20,0-8,0-20,0"}
Returns: 1
The union of these two polylines is the line segment 0,0-20,0.
5)
    
{"1,1 2,2 3,3 4,4 3,3-4,4"}
Returns: 3
A single point is a special case of a polyline.
6)
    
{"10,10-20,10 20,10-15,18 15,18-10,10"}
Returns: 1
A triangle.
7)
    
{"1,1 1,1"}
Returns: 1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AncientLanguage

Graph Theory, String Manipulation



Used in:

TCCC07 Semi 1

Used as:

Division I Level Three

Writer:

andrewzta

Testers:

PabloGilberto , vorthys , Olexiy , misof , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8248

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10956&pm=8248

Problem Statement

    

Scientists have discovered a text in some ancient language. The text is written using two types of hieroglyphs. We will denote the hieroglyphs of the first type with uppercase letters ('A'-'Z'), and the hieroglyphs of the second type with lowercase letters ('a'-'z'). The types of hieroglyphs in the text alternate, meaning that every pair of adjacent hieroglyphs have different types. For example, "AaAbBaAcCaAa" is a valid example of the text, but "ACbD" is not.

Scientists have a hypothesis that the text they have found is a sequence of words. Each word in this language consists of a pair of hieroglyphs of different types. For example, "Aa", "bB", "bC" are valid examples of words.

Words in text can overlap, so, for example, "AaAbB" can be viewed as the sequence of words ("Aa", "aA", "bB").

Now scientists want to know the minimal possible number of different words the text can contain. For example, the text "AaAbBaAcCaAa" can be interpreted as the sequence of words ("Aa", "aA", "bB", "aA", "cC", "aA", "Aa"), which uses only four different words: "Aa", "aA", "bB", "cC".

You are given a String[] t. The text is the concatenation of all the elements of t. Return the minimal number of different words that the text can contain.

 

Definition

    
Class:AncientLanguage
Method:minWords
Parameters:String[]
Returns:int
Method signature:int minWords(String[] t)
(be sure your method is public)
    
 

Constraints

-t will contain between 1 and 50 elements, inclusive.
-Each element of t will contain between 1 and 50 characters, inclusive.
-Each element of t will contain only letters ('A'-'Z', 'a'-'z').
-The total number of characters in t will be between 2 and 2500, inclusive.
-In the concatenation of all elements of t, letters will alternate between uppercase and lowercase.
 

Examples

0)
    
{"AaAbBaAcCaAa"}
Returns: 4
An example from the problem statement.
1)
    
{"AbAb"}
Returns: 1
The first letter in the text can be uppercase.
2)
    
{"aBaB"}
Returns: 1
The first letter in the text can be lowercase.
3)
    
{"AaB", "b"}
Returns: 2
You must concatenate all elements of t before processing.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BinaryCodes

Graph Theory, Search, String Manipulation



Used in:

SRM 368

Used as:

Division I Level Three

Writer:

misof

Testers:

PabloGilberto , vorthys , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8247

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10936&pm=8247

Problem Statement

    

Given a finite alphabet S, a binary code over this alphabet S is a function that maps each element of S to some (possibly empty) string over the alphabet {0,1}.

An example of such a code for S={a,b,c,d} is the function f defined by f(a)=1, f(b)=1010, f(c)=01, f(d)=10101.

Any binary code can be naturally extended to encode strings over the alphabet S simply by concatenating the codes of the string's letters, in order. For example, using the code mentioned above we can encode cac as f(cac)=01101.

A code is called ambiguous if there are two different strings over S that have the same encoding. Obviously, in practice we want to avoid using an ambiguous code.

A code is called really ambiguous if there are three different strings over S that have the same encoding. For example, the code from the above example is really ambiguous: the strings ba, acc, and d are all encoded to 10101.

You will be given a String[] code containing the strings over {0,1} used to encode letters of some alphabet S. Your method should check whether this code is really ambiguous. If it is really ambiguous, find a shortest string over {0,1} that is an encoding of (at least) three different strings over S, and return its length. If the given code is not really ambiguous, return -1.

 

Definition

    
Class:BinaryCodes
Method:ambiguous
Parameters:String[]
Returns:int
Method signature:int ambiguous(String[] code)
(be sure your method is public)
    
 

Notes

-Your method does not need to know the actual elements of S, and the size of S is obviously equal to the number of elements in code.
 

Constraints

-code will contain between 2 and 30 elements, inclusive.
-Each element of code will contain between 0 and 50 characters, inclusive.
-Each element of code will only contain the characters '0' (zero) and '1' (one).
 

Examples

0)
    
{"1","1010","01","10101"}
Returns: 5
This is the example from the problem statement, and the string 10101 is the shortest string that can be decoded in three different ways.
1)
    
{"0","1"}
Returns: -1
This code is obviously not ambiguous.
2)
    
{"0","11","11","11"}
Returns: 2
This is clearly a really ambiguous code, as there are three different one letter strings over S that are encoded to 11.
3)
    
{"0000","001","01001","01010","01011"}
Returns: -1
This code is a prefix code, i.e., no code word is a prefix of another code word. If a code has this property, it is guaranteed that it is not ambiguous, but the other direction is not true.
4)
    
{"1","10","00"}
Returns: -1
This is not a prefix code, but it can easily be shown that this code is not ambiguous.
5)
    
{"","01101001001","111101011"}
Returns: 0
Having an empty code word is a great way how to design a really ambiguous code.
6)
    
{"00011011","000110","11","0001","1011","00","011011"}
Returns: 8
The shortest proof that this code is really ambiguous is 00011011. Note that this string can in fact be decoded in four different ways.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

JumpingBoard

Graph Theory, Recursion, Search



Used in:

SRM 368

Used as:

Division I Level One , Division II Level Three

Writer:

misof

Testers:

PabloGilberto , vorthys , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8245

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10936&pm=8245

Problem Statement

    

You are given a rectangular board where each cell contains either an integer between 1 and 9, inclusive, or a hole.

Place a token into the cell in the upper left corner of the board. Now you can play a simple game. The game consists of moves, and each move looks as follows:

  • Look at the number X written in the cell where your token is placed.
  • Choose one of the four basic directions (up, down, left, or right).
  • Move your token exactly X cells in the chosen direction. You can jump over all intermediate holes in the path.

The game ends after a move that lands the token in a hole or outside the board. Your goal is to make as many moves as possible.

The board is given as a String[] board. Characters '1' to '9' represent cells containing the corresponding integer, and letters 'H' represent holes. The upper left corner of the board corresponds to the first character of the first element of board.

Write a method that will compute the maximum number of moves you can make on the given board. If it is possible to make an arbitrarily large number of moves, your method should return -1.

 

Definition

    
Class:JumpingBoard
Method:maxJumps
Parameters:String[]
Returns:int
Method signature:int maxJumps(String[] board)
(be sure your method is public)
    
 

Constraints

-board will contain between 1 and 50 elements, inclusive.
-Each element of board will contain between 1 and 50 characters, inclusive.
-All elements of board will be of the same length.
-Each element of board will only contain characters from the string "123456789H" (quotes for clarity).
-The first character of the first element of board will not be 'H'.
 

Examples

0)
    
{"3942178",
 "1234567",
 "9123532"}
Returns: 5
In the first move you have to move the token to the right. In the second move you have three choices. Moves to the left and to the right would bring you to cells with a 9 and a 7, respectively, forcing you to end the game in the third move. The optimal strategy is to make the second move down, the third one to the right, and the fourth one up or to the left. In the last fifth move you are forced to leave the board.
1)
    
{"2H3HH4HHH5"}
Returns: 4
Remember that you are allowed to jump over holes. Only landing in a hole is bad.
2)
    
{"3994",
 "9999",
 "9999",
 "2924"}
Returns: -1
Make the first move down, and then you can jump left and right as many times as you wish.
3)
    
{"123456",
 "234567",
 "345678",
 "456789"}
Returns: 4
On this board, all moves that don't end the game lead to the right or down. In the best solution, the first three moves are: right, down, right.
4)
    
{"9"}
Returns: 1
There is no real choice here. The game will always end after the first move.
5)
    
{"2H9HH11",
 "HHHHH11",
 "9HHHH11"}
Returns: 2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FloodRelief

Graph Theory, Recursion



Used in:

SRM 371

Used as:

Division II Level Three

Writer:

bmerry

Testers:

PabloGilberto , Yarin , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8243

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10787&pm=8243

Problem Statement

    

Global warming has caused your home town to receive far more rain than usual, and it is in danger of becoming flooded. You have been put in charge of buying and installing pumps that will carry away the water. There is no limit on how much water a pump can handle, but they must be placed correctly so that all the water will flow into a pump, with no lakes or even puddles left over. The pumps are also expensive, so you must determine the minimum number that need to be bought.

You are given a String[] heights. This is a rectangular grid representing the height of each square meter of your town. It contains only lowercase letters ('a' - 'z'), with 'a' meaning low ground and 'z' meaning high ground. Water flows from a cell to every cell that shares an edge and is of equal or lower height. The town is surrounded by high mountains on all sides, so water cannot flow off the map. You must return the minimum number of pumps that can be placed to ensure that all rain will eventually flow to some pump.

 

Definition

    
Class:FloodRelief
Method:minimumPumps
Parameters:String[]
Returns:int
Method signature:int minimumPumps(String[] heights)
(be sure your method is public)
    
 

Constraints

-heights will contain between 1 and 50 elements, inclusive.
-Each element of heights will contain between 1 and 50 characters, inclusive.
-Each element of heights will contain the same number of characters.
-Each element of heights will contain only lowercase letters ('a' - 'z').
 

Examples

0)
    
{"ccccc",
 "cbbbc",
 "cbabc",
 "cbbbc",
 "ccccc"}
Returns: 1
A bowl-shaped area. A single pump in the center is sufficient.
1)
    
{"cbabcbabc",
 "cbabcbabc",
 "cbabcbabc",
 "cbabcbabc"}
Returns: 2
Two valleys separated by a ridge. Each valley needs a pump.
2)
    
{"ccccccccccc",
 "caaaaaaaaac",
 "caaaaaaaaac",
 "caazpppzaac",
 "caapdddpaac",
 "caapdddpaac",
 "caapdddpaac",
 "caazpppzaac",
 "caaaaaaaaac",
 "caaaaaaaaac",
 "ccccccccccc"}
Returns: 2
A castle with a central courtyard and a moat. One pump is needed for each.
3)
    
{"ab",
 "ba"}
Returns: 2
Water cannot flow diagonally.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

HockeyFault

Geometry



Used in:

SRM 374

Used as:

Division II Level One

Writer:

jbernadas

Testers:

PabloGilberto , Olexiy , Andrew_Lazarev

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8224

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10793&pm=8224

Problem Statement

    

Last week, MyOwnBusiness Inc. received an urgent call from the IIHF (International Ice Hockey Federation) requesting a system to raise an alarm to the referee when there are too many players from the same team inside the rink. The system will be composed of three parts:

  1. A digital camera in the ceiling to take photos of the rink every second.
  2. A software module to extract the position of each player from the photo taken by the digital camera.
  3. A software module to count the number of players from the same team inside the hockey rink.

The hockey rink consists of a width x height rectangle whose lower-left corner is at (x, y), and two circles with radius height / 2, one centered at (x, y + radius) and the other centered at (x + width, y + radius). See the image below for a graphic description. The players are specified by the int[]s px and py, where the k-th player's position is (px[k], py[k]).





You have been assigned the task of implementing the system's third module, following the specification given by the project leader: "Given the rink's specification and the players' positions, create a method numPlayers that returns the number of players on the boundary or inside the rink."

 

Definition

    
Class:HockeyFault
Method:numPlayers
Parameters:int, int, int, int, int[], int[]
Returns:int
Method signature:int numPlayers(int width, int height, int x, int y, int[] px, int[] py)
(be sure your method is public)
    
 

Notes

-For those who know about ice hockey, the rink described in this problem is different than a real hockey rink.
 

Constraints

-width will be between 1 and 100, inclusive.
-height will be between 2 and 100, inclusive.
-height will be an even number.
-x will be between -100 and 100, inclusive.
-y will be between -100 and 100, inclusive.
-px will contain between 1 and 50 elements, inclusive.
-Each element of px will be between -300 and 300, inclusive.
-py will contain the same number of elements as px.
-Each element of py will be between -300 and 300, inclusive.
 

Examples

0)
    
20
10
5
0
{15, 1, 1}
{5, 5, 1}
Returns: 2
The first player is exactly in the middle of the rink, the second player is exactly at the left border of the left circle and the third player is outside the rink.
1)
    
20
10
0
0
{-5, -4, -4, -3, -3, 0, 0, 20, 20, 23, 23, 24, 24, 25}
{5, 2, 8, 1, 9, 0, 10, 0, 10, 1, 9, 2, 8, 5}
Returns: 14
All players are on the rink boundary.
2)
    
52
84
-44
66
{26, -33, -49, 40, -10, 47, 25, -16, -82, 7}
{118, 106, 128, 114, 101, 85, 142, 140, 126, 145}
Returns: 8
3)
    
24
100
-61
71
{-63, -26, -9, -113, -124, -95, -89, -55}
{109, 164, 91, 80, 75, 140, 116, 113}
Returns: 6

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LinearCity

Graph Theory



Used in:

TCHS SRM 39

Used as:

Division I Level Two

Writer:

jbernadas

Testers:

PabloGilberto , brett1479 , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8187

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10782&pm=8187

Problem Statement

    

In some cities, when you ask for the location of a place, people give you a specific address. LinearCity, on the other hand, is one-dimensional, so people just tell you to walk either left or right from your current location until you reach your desired location.



Over time, you have collected information about the relative positions of pairs of places in LinearCity. This information is given in the String refDirection and the int[]s refSource and refDestination. The i-th element of refDirection is the direction you need to walk (either 'L' or 'R', quotes for clarity) to get from refSource[i] to refDestination[i] (each place in the city is represented by a distinct integer between 0 and N-1, inclusive, where N is the total number of places in the city). You know that all the information is consistent, meaning that there is no place that is both to the left and to the right of another place.



You are arranging a tour for newcomers to the city, and you need to know the directions between various places. Your are given int[]s source and destination, each containing the same number of elements. Return a String[] where the i-th element is the direction you must walk to get from source[i] to destination[i]. If the direction cannot be deduced, the corresponding element should be "UNKNOWN" (quotes for clarity). Otherwise, it should be either "LEFT" of "RIGHT" (quotes for clarity).



 

Definition

    
Class:LinearCity
Method:getReference
Parameters:int[], int[], String, int, int[], int[]
Returns:String[]
Method signature:String[] getReference(int[] refSource, int[] refDestination, String refDirection, int N, int[] source, int[] destination)
(be sure your method is public)
    
 

Constraints

-refSource will contain between 1 and 50 elements, inclusive.

-Each element of refSource will be between 0 and N-1, inclusive.

-refDestination will contain the same number of elements as refSource.

-Each element of refDestination will be between 0 and N-1, inclusive.

-refSource[i] will be different than refDestination[i], for all i between 0 and M-1, where M is the size of refSource.

-refDirection will contain the same number of characters as the number of elements in refSource.

-Each character in refDirection will be 'L' or 'R'.

-N will be between 2 and 50, inclusive.

-source will contain between 1 and 50 elements, inclusive.

-Each element of source will be between 0 and N-1, inclusive.

-destination will contain the same number of elements as source.

-Each element of destination will be between 0 and N-1, inclusive.

-source[i] will be different than destination[i], for all i between 0 and K-1, where K is the size of source.

-All references will be consistent, as explained in the problem statement.

 

Examples

0)
    
{1, 2}
{2, 0}
"RR"
3
{1, 0}
{0, 1}
Returns: {"RIGHT", "LEFT" }
If you can go from 1 to 2 walking to the right and you can go from 2 to 0 walking to the right, then you can go from 1 to 0 walking to the right passing by 2. Finally, if you can go from 1 to 0 walking to the right, then you can go from 0 to 1 walking to the left.
1)
    
{1, 0}
{2, 2}
"RL"
3
{1, 0}
{0, 1}
Returns: {"RIGHT", "LEFT" }
This is the same case as Example 0, but with the direction between 0 and 2 reversed.
2)
    
{2, 3, 1, 0, 2, 0, 5, 5}
{1, 4, 4, 4, 4, 3, 2, 3}
"RLRLRLLL"
6
{0, 1, 0}
{2, 3, 5}
Returns: {"LEFT", "RIGHT", "UNKNOWN" }
You can go from 0 to 2 walking to left passing through places 3, 4 and 1, in order. Similarly, you can go from 1 to 3 walking to the right passing through place 4. However, it is impossible to find a unidirectional path from 0 to 5 using the given references.
3)
    
{1, 0, 2, 3}
{0, 2, 3, 2}
"RRRL"
5
{0, 2, 3, 0, 4}
{2, 4, 1, 1, 0}
Returns: {"RIGHT", "UNKNOWN", "LEFT", "LEFT", "UNKNOWN" }
It is possible to have repeated references, and to have a query about a place not mentioned in the given references.
4)
    
{6, 0, 0, 5, 2, 4, 1, 1, 1, 6, 2, 0, 2, 2, 3, 1, 5, 1, 5, 6, 0}
{4, 6, 4, 2, 6, 3, 2, 4, 5, 5, 3, 1, 0, 4, 0, 6, 4, 3, 3, 3, 5}
"RLRLRRRRRRRLRRLRRRRRL"
7
{5, 6, 2, 4, 6, 2, 4}
{0, 0, 0, 5, 2, 5, 6}
Returns: {"RIGHT", "RIGHT", "RIGHT", "LEFT", "LEFT", "RIGHT", "LEFT" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CoolFunction

Simple Math



Used in:

TCO08 Championship

Used as:

Division I Level One

Writer:

ivan_metelsky

Testers:

PabloGilberto , SnapDragon , Olexiy , Mike Mirzayanov

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8180

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12019&pm=8180

Problem Statement

    

The function f: R -> R is called cool if there are integer numbers a0 <= a1 <= ... <= ak-1 (k >= 1) such that f(x) = |x - a0| + |x - a1| + ... + |x - ak-1| for every real value of x.

You will be given a int[] values, containing n elements. You should find a cool function f such that f(i) = values[i] for every i, where 0 <= i < n. Return a int[], containing the values a0, a1, ..., ak-1 for this function. If there are many possible answers, choose the one with the smallest number of elements. If tie still exists, return the lexicographically smallest int[]. Constraints will guarantee that values corresponds to at least one cool function.

 

Definition

    
Class:CoolFunction
Method:restore
Parameters:int[]
Returns:int[]
Method signature:int[] restore(int[] values)
(be sure your method is public)
    
 

Constraints

-values will contain between 1 and 50 elements, inclusive.
-Each element of values will be between 0 and 50, inclusive.
-values will correspond to at least one cool function.
 

Examples

0)
    
{0}
Returns: {0 }
|x| is acceptable here.
1)
    
{50}
Returns: {-50 }
Here there are two variants with k=1: |x-50| and |x+50|. The second one is lexicographically smaller.
2)
    
{2, 4}
Returns: {-2, 0 }
3)
    
{3, 3}
Returns: {-2, 1 }
4)
    
{5, 1}
Returns: {1, 1, 1, 2 }
The return is not necessarily strictly increasing.
5)
    
{10, 4, 6}
Returns: {1, 1, 1, 1, 2, 4 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CompoundHypergraphDrawing

Graph Theory



Used in:

MM 24

Used as:

Division I Level One

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8168

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10930&pm=8168

Problem Statement

    A compound hypergraph consists of a set V of nodes and a set E of hyperedges connecting sets of those nodes. Each node v in V may have a parent node, given by parent(v). Each hyperedge consists of a subset of the nodes in V. Your task in this problem is to create a visually appealing layout of a compound hypergraph.



In this layout, each node will be represented by a rectangle, and each node will have a minimum height and width requirement. Each hyperedge will be represented by a number of horizontal, vertical, or diagonal (at 45 degree angle) line segments. The segments from one hyperedge should create a path from each node in the hyperedge to each other node in the hyperedge. A segment connects to a node if it touches the rectangle defining that node at any point.



The layout must meet all of the following requirements:
  1. Each set of segments forming a hyperedge must connect all the nodes in that hyperedge.
  2. Each node must meet or exceed its minimum size requirements.
  3. Each segment must be horizontal, vertical, or diagonal.
  4. Each node must be entirely contained within its parent node (the boundaries may not touch).
  5. No two segments may overlap at more than one point (be on top of each other).
  6. No segment may overlap any rectangle edge of any node at more than one point (be on top of its edge).
  7. No segment may touch another segment at its endpoint unless they are part of the same hyperedge.
  8. A segment in an edge may not cross (or touch) the boundary of a node unless that node is an ancestor of some of the nodes being connected, and not an ancestor of some other nodes being connected, or that node is one of the ones being connected. In other words, it may not cross a node boundary unless doing so is necessary to connect the nodes in the hyperedge.
  9. No two nodes may overlap, except in the case where one is contained entirely inside one of its ancestors.
  10. Each coordinate defining a rectangle or segment must be an integer.


For instance, consider the example shown by this image. C is the parent of A and B, while M is the parent of C, D, E, and F. Similarly, N is the parent of G-L. M and N have no parent. The hyperedges consist of the following sets: (A,B), (C,D,E,F), (D,F,G,K,L), (G,H), (G,I), and (G,J,K). Note, for instance, the three segments which connect C, D, E and F. On the other hand, 7 segments are used to connect D, F, G, K, and L.



You will be given the input as a int[] parents where element i of parents is -1 if node i has no parent, and otherwise denotes the parent of node i. You will also be given a String[], hyperedges, where each element is a single-space delimited list of two or more nodes forming a hyperedge. Finally, elements i of width and height will give the minimum width and height requirements for node i.



For each node, you should return the coordinates of the rectangle corresponding to that node, formated as "NODE <node_id> <x1> <y1> <x2> <y2>". For each hyperedge, you should return a list of segments "EDGE <edge_id> <x1> <y1> <x2> <y2> ... <xn> <yn>", where (x2i-1,y2i-1) and (x2i,y2i) specify a segment for each i. The <edge_id> and <node_id> correspond to the indices of the inputs (starting from 0).



Scoring is based on crossings, total length, total size, and number of segments. Each crossing of two segments from different hyperedges will incur a cost of C. Each unit of length in segments will incur a cost of L. Each segment will incur a cost of S. Finally the perimeter of the bounding box around your drawing will incur a cost of P per unit. For each test case, your score will be BEST/YOU, where BEST is the lowest cost incurred on a test case. Invalid returns or program crashes will be treated as a cost of infinity, yielding 0 points for the test case.



Test data will be generated by sampling from a large dataset from a real problem. The sampling process is complicated, and hence a corpus of samples may be downloaded for testing purposes. No more tests will be provided, and the exact process by which the tests are generated will not be further described. All of the minimum width and height requirements will be chosen randomly between 5 and 25, inclusive. Examples may be downloaded at www.topcoder.com/contest/problem/CompoundHypergraphDrawing/examples, while 10,000 other tests may be downloaded from www.topcoder.com/contest/problem/CompoundHypergraphDrawing/tests.gz. Additionally, a simple tool is provided for visualizing your drawings at www.topcoder.com/contest/problem/CompoundHypergraphDrawing/vis.html.
 

Definition

    
Class:CompoundHypergraphDrawing
Method:draw
Parameters:int[], int[], int[], String[], int, int, int, int
Returns:String[]
Method signature:String[] draw(int[] parent, int[] width, int[] height, String[] hyperedges, int C, int L, int S, int P)
(be sure your method is public)
    
 

Notes

-The memory limit is 1024M and the time limit is 2 minutes.
-If two segments from the same hyperedge cross, they are considered connected, and this does not count as a crossing.
-If more than two segments cross at the same point, each pair will count as a crossing.
-All coordinates must be in [-100000,100000].
-Lines have no width.
-You may use at most 1000 segments.
-The largest test case in the tests file has 99 nodes. The average is 59 nodes and 8.6 hyperedges.
-Overlapping includes touching.
-No hyperedge will include a node and one of its ancestors.
 

Constraints

-All the following ranges are selected uniformly at random and are inclusive.
-C will be between 200 and 400.
-L will be between 1 and 3.
-S will be between 5 and 20.
-P will be between 1 and 5.
 

Examples

0)
    
"N 0 -1,N 1 0,N 2 -1,N 3 2,N 4 -1,N 5 4,N 6 -1,N 7 6,N 8 -1,N 9 8,N 10 -1,N 11 10,N 12 -1,N 13 12,N 14 -1,N 15 14,E 1 3,E 13 15,"
Returns: "16 nodes and 2 hyperedges.
Seed = -1856808928
C = 380
L = 1
S = 13
P = 1"
1)
    
"N 0 -1,N 1 0,N 2 -1,N 3 2,N 4 -1,N 5 4,N 6 -1,N 7 6,N 8 -1,N 9 8,N 10 2,N 9 8,N 11 2,N 12 -1,N 13 12,N 14 -1,N 15 14,N 16 -1,N 17 16,E 1 3,E 5 7,E 9 10,E 9 11,E 13 15,"
Returns: "18 nodes and 5 hyperedges.
Seed = -1790372174
C = 330
L = 3
S = 14
P = 1"
2)
    
"N 0 -1,N 1 0,N 2 -1,N 3 2,N 4 -1,N 5 4,N 6 -1,N 7 6,N 8 6,N 9 -1,N 10 9,N 11 9,N 12 -1,N 13 12,N 14 12,N 15 -1,N 16 15,N 17 -1,N 18 17,E 1 3,E 7 8,E 10 11,E 13 14,E 16 18,"
Returns: "19 nodes and 5 hyperedges.
Seed = -255016001
C = 248
L = 1
S = 12
P = 5"
3)
    
"N 0 -1,N 1 -1,N 2 1,N 3 -1,N 4 3,N 5 -1,N 6 5,N 7 5,N 8 -1,N 9 8,N 10 -1,N 11 10,N 12 3,N 13 -1,N 14 13,N 15 13,N 16 1,N 17 3,N 18 -1,N 19 18,N 20 8,N 21 10,E 2 4,E 6 7,E 9 11,E 14 15,E 16 17,E 20 21,"
Returns: "22 nodes and 6 hyperedges.
Seed = -1241721039
C = 388
L = 3
S = 5
P = 2"
4)
    
"N 0 -1,N 1 0,N 2 -1,N 3 2,N 4 -1,N 5 4,N 6 4,N 7 -1,N 8 7,N 9 -1,N 10 9,N 11 -1,N 12 11,N 13 -1,N 14 13,N 15 -1,N 16 15,N 17 -1,N 18 17,N 19 -1,N 20 19,N 21 19,N 1 0,N 22 2,N 23 0,N 24 9,N 25 -1,N 26 25,N 27 9,N 28 -1,N 29 28,N 30 -1,N 31 30,E 1 3,E 5 6,E 8 10,E 12 14,E 16 18,E 20 21,E 1 22,E 23 24,E 26 27,E 29 31,"
Returns: "32 nodes and 10 hyperedges.
Seed = 1933896167
C = 283
L = 3
S = 20
P = 2"
5)
    
"N 0 -1,N 1 0,N 2 -1,N 3 2,N 4 -1,N 5 4,N 6 -1,N 7 6,N 8 -1,N 9 8,N 10 -1,N 11 10,N 12 -1,N 13 12,N 14 -1,N 15 14,N 16 -1,N 17 16,N 18 -1,N 19 18,N 20 -1,N 21 20,N 22 -1,N 23 22,N 24 25,N 26 -1,N 27 26,N 28 -1,N 29 28,N 30 -1,N 31 30,N 32 -1,N 33 32,N 34 -1,N 35 34,N 36 -1,N 37 36,N 38 -1,N 39 38,N 25 36,N 40 -1,N 41 40,N 27 26,N 42 -1,N 43 42,N 44 32,N 31 30,N 33 32,N 45 -1,N 46 45,N 47 32,E 3 5,E 7 9 11 13 15 17 19 21 23 24 27 29,E 31 33,E 35 37,E 39 25,E 41 27,E 43 44,E 31 33,E 46 47,"
Returns: "48 nodes and 9 hyperedges.
Seed = 1825782255
C = 200
L = 3
S = 15
P = 3"
6)
    
"N 0 -1,N 1 0,N 2 -1,N 3 2,N 4 -1,N 5 4,N 6 -1,N 7 6,N 8 6,N 9 -1,N 10 9,N 11 -1,N 12 11,N 13 -1,N 14 13,N 15 13,N 16 13,N 17 -1,N 18 17,N 19 -1,N 20 19,N 21 19,N 22 19,N 23 -1,N 24 23,N 25 -1,N 26 25,N 27 25,N 28 -1,N 29 28,N 30 28,N 31 -1,N 32 31,N 33 31,N 34 31,N 35 31,N 36 31,N 37 -1,N 38 37,N 39 -1,N 40 39,N 41 -1,N 42 41,N 43 41,N 44 -1,N 45 44,N 46 -1,N 47 46,N 48 -1,N 49 48,N 50 -1,N 51 50,E 1 3,E 7 8,E 10 12 14 15 16 18 20 21 22 24 26 27 29 30 32 33 34 35 36 38 40 42 43,E 45 47,E 49 51,"
Returns: "52 nodes and 5 hyperedges.
Seed = 1111485637
C = 314
L = 2
S = 13
P = 3"
7)
    
"N 0 -1,N 1 0,N 2 0,N 3 -1,N 4 -1,N 5 4,N 1 0,N 6 0,N 7 -1,N 8 7,N 9 -1,N 10 9,N 11 9,N 12 -1,N 13 12,N 14 -1,N 15 14,N 16 -1,N 17 16,N 18 -1,N 19 18,N 20 18,N 21 -1,N 22 21,N 23 12,N 24 -1,N 25 24,N 26 16,N 27 -1,N 28 27,N 29 4,N 30 -1,N 31 30,N 32 -1,N 33 32,N 34 -1,N 35 34,N 36 16,N 37 16,N 38 -1,N 39 38,N 40 38,N 41 -1,N 42 -1,N 43 42,N 44 -1,N 45 44,N 46 -1,N 47 46,N 48 -1,N 49 48,N 50 -1,N 51 50,E 1 2,E 1 6,E 10 11,E 15 17,E 19 20,E 22 23,E 25 26,E 28 29,E 31 33,E 35 36,E 39 40,E 43 45 47 49,"
Returns: "52 nodes and 12 hyperedges.
Seed = -55340767
C = 272
L = 1
S = 19
P = 5"
8)
    
"N 0 -1,N 1 0,N 2 -1,N 3 2,N 4 -1,N 5 4,N 6 2,N 7 -1,N 8 7,N 6 2,N 9 4,N 10 -1,N 11 10,N 12 10,N 13 -1,N 14 13,N 15 -1,N 16 15,N 17 13,N 18 13,N 19 -1,N 20 19,N 21 -1,N 22 21,N 23 -1,N 24 23,N 25 -1,N 26 25,N 27 25,N 28 25,N 29 -1,N 30 29,N 31 29,N 32 29,N 33 -1,N 34 33,N 35 -1,N 36 35,N 37 35,N 38 -1,N 39 38,N 40 0,N 41 -1,N 42 41,N 43 -1,N 44 43,N 45 -1,N 46 45,N 47 0,N 48 -1,N 49 48,N 50 48,N 51 -1,N 52 51,N 53 -1,N 54 53,E 3 5,E 6 8,E 6 9,E 11 12,E 14 16 17 18 20 22 24 26 27 28 30 31 32 34 36 37 39,E 42 44,E 46 47,E 49 50,E 52 54,"
Returns: "55 nodes and 9 hyperedges.
Seed = 1142965478
C = 285
L = 3
S = 6
P = 1"
9)
    
"N 0 -1,N 1 0,N 2 0,N 3 -1,N 4 3,N 5 -1,N 6 5,N 7 -1,N 8 7,N 9 -1,N 10 9,N 11 -1,N 12 11,N 13 -1,N 14 13,N 15 -1,N 16 15,N 17 -1,N 18 17,N 19 -1,N 20 19,N 21 -1,N 22 21,N 23 -1,N 24 23,N 25 23,N 26 -1,N 27 26,N 28 26,N 29 26,N 30 -1,N 31 30,N 32 -1,N 33 32,N 34 -1,N 35 34,N 36 34,N 37 -1,N 38 37,N 39 -1,N 40 39,N 41 -1,N 42 41,N 43 41,N 44 41,N 45 41,N 46 41,N 47 -1,N 48 47,N 49 47,N 50 -1,N 51 50,N 52 -1,N 53 52,N 54 52,N 55 52,N 56 -1,N 57 56,N 58 56,N 59 56,N 60 -1,N 61 60,N 62 -1,N 63 62,N 64 -1,N 65 64,N 66 64,N 67 -1,N 68 67,N 69 67,N 70 67,N 71 -1,N 72 71,N 73 71,N 74 71,N 75 -1,N 76 75,N 77 75,N 78 -1,N 79 78,N 80 -1,N 81 80,N 82 -1,N 83 82,N 84 -1,N 85 84,N 86 84,N 87 -1,N 88 87,N 89 87,N 90 87,N 91 87,N 92 87,N 93 87,N 94 87,N 95 87,E 1 2,E 4 6,E 8 10,E 12 14 16 18 20 22 24 25 27 28 29 31 33 35 36 38 40 42 43 44 45 46 48 49 51 53 54 55 57 58 59 61 63 65 66 68 69 70 72 73 74 76 77 79 81 83 85 86 88 89 90 91 92 93 94 95,"
Returns: "96 nodes and 4 hyperedges.
Seed = -405961877
C = 285
L = 2
S = 13
P = 4"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DogField

Brute Force, Graph Theory



Used in:

TCHS SRM 44

Used as:

Division I Level Three

Writer:

boba5551

Testers:

PabloGilberto , brett1479 , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8159

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10795&pm=8159

Problem Statement

    

d dogs and d dog-houses are located on a rectangular field of n * m squares. It is raining now, so each dog wants to get into a dog-house as soon as possible, but each dog-house can accomodate only 1 dog. To make the task harder, some squares of the field contain rocks which make those squares impassable. Dogs cannot pass through squares with dog-houses either, but they can enter empty dog-houses. Once a dog enters a dog-house, it can never leave it. Dogs are very friendly, so a dog can pass through an empty square even if there are other dogs on it.

A String[] field will give you the map of the field. Each character of field will be an uppercase 'D' (representing an empty square with a dog on it), an uppercase 'H' (a dog-house), an uppercase 'R' (a rock) or a '.' (an empty square). Dogs can only move between neighboring squares (two squares are neighboring if they share a side), and it takes 1 second to move from one square to another. At most one dog can move at the same time. The dogs may never leave the field. Return the minimal total time required for all the dogs to end up in dog-houses. If at least one dog cannot reach an empty dog-house, return -1 instead.

 

Definition

    
Class:DogField
Method:saveDogs
Parameters:String[]
Returns:int
Method signature:int saveDogs(String[] field)
(be sure your method is public)
    
 

Notes

-Initially, every dog is on an empty square (i.e., not on a square containing a dog-house, rock, or another dog).
 

Constraints

-field will contain between 1 and 50 elements, inclusive.
-Each element of field will contain between 1 and 50 characters, inclusive.
-All elements of field will contain same number of characters.
-Each character in each element of field will be an uppercase 'R', an uppercase 'H' , an uppercase 'D' or a '.'.
-field will contain between 1 and 10 'D' characters, inclusive.
-The number of 'D' and 'H' characters in field will be the same.
 

Examples

0)
    
{"D..H..H",
 ".D...DD",
 ".H..H.."}
Returns: 7
The dog at row 0, column 0 will move three squares right. The dog at row 1, column 1 will move one square down. The dog at row 1, column 5 will move one square left and one square down. The dog at row 1, column 6 will move one square up. The total time needed to save all the dogs is 3 + 1 + 2 + 1 = 7.
1)
    
{"D..RH",
 "...RR",
 "....."}
Returns: -1
The dog cannot reach the dog-house because it is surrounded by rocks.
2)
    
{"...RRRR.",
 "D..RH...",
 "..RRRRR.",
 "........"}
Returns: 14
The only dog will move to the only dog-house by the path marked by 'U' characters:
...RRRR.
D..RHUUU
U.RRRRRU
UUUUUUUU
3)
    
{"D",
 "H"}
Returns: 1
The dog only needs to move one square to reach the dog-house.
4)
    
{"DDD..RH.H.H",
 "DDD..R.H.H.",
 "DD.........",
 "DD...RHHHHH"}
Returns: 96

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CountExpressions

Brute Force, Simple Math



Used in:

SRM 398

Used as:

Division I Level One , Division II Level Two

Writer:

boba5551

Testers:

PabloGilberto , legakis , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8157

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12170&pm=8157

Problem Statement

    

You are helping your brother with his homework assignment. His teacher gave him two distinct numbers x and y, and asked him to use those numbers to form as many different expressions as possible. Each expression must satisfy all of the following rules:

  1. The only allowed operators are '+', '-' and '*'.
  2. x and y must each appear exactly twice. No other numbers are allowed.
  3. The result of the expression must be equal to val.



In other words, each expression can be written in the form "a op1 b op2 c op3 d", where each of op1, op2 and op3 is '+', '-' or '*', and among the numbers a, b, c and d, exactly two are equal to x and the other two are equal to y. Please note that the unary minus is not allowed (see example 0). Expressions are calculated from left to right, and there is no operator precedence. For example, to calculate the result of "2 + 2 * 3 + 3", you would first calculate 2 + 2, then multiply the result by 3, and then add 3 to get 15.



Return the total number of different expressions that can be formed. Two expressions are considered different if their string notations (as described in the previous paragraph) are different. For example, the expressions "2 + 3 - 2 - 3", "2 - 2 + 3 - 3" and "2 - 3 - 2 + 3" are all different.

 

Definition

    
Class:CountExpressions
Method:calcExpressions
Parameters:int, int, int
Returns:int
Method signature:int calcExpressions(int x, int y, int val)
(be sure your method is public)
    
 

Constraints

-x and y will each be between -100 and 100, inclusive.
-x and y will be different.
-val will be between -100000000 and 100000000, inclusive.
 

Examples

0)
    
7
8
16
Returns: 9
The possible expressions are:
8 + 8 + 7 - 7
8 + 7 + 8 - 7
7 + 8 + 8 - 7
8 + 8 - 7 + 7
8 + 7 - 7 + 8
7 + 8 - 7 + 8
8 - 7 + 8 + 7
8 - 7 + 7 + 8
7 - 7 + 8 + 8
Please note that the unary minus is not allowed, so "-7 + 7 + 8 + 8" is not a valid expression.
1)
    
3
5
7
Returns: 5
The possible expressions are:

3 * 5 - 3 - 5
5 * 3 - 3 - 5
3 * 5 - 5 - 3
5 * 3 - 5 - 3
5 - 3 * 5 - 3
2)
    
99
100
98010000
Returns: 6
3)
    
-99
42
-1764
Returns: 2
-99 - (-99) - 42 * 42
-99 - 42 - (-99) * 42
4)
    
100
-100
-100000000
Returns: 0
There are no valid expressions.
5)
    
1
2
5
Returns: 17

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SoftwareCompanies

Graph Theory



Used in:

SRM 404

Used as:

Division I Level Three

Writer:

boba5551

Testers:

PabloGilberto , Yarin , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8155

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12176&pm=8155

Problem Statement

    

There are several companies on the market, with each company processing some data in order to produce data in a new company-specific format. When a company gets a unit of input data, it produces a unit of new data. Unfortunately, each company can process only some limited amount of data, and each company can accept only some specific data formats. Of course, running each company costs the owner some money.

The information about the companies will be given to you in a String[] names, a String[] process, a int[] cost and a int[] amount. names[i] is the name of the i-th company. process[i] is a single-space delimited list of companies which can process the data produced by the i-th company. cost[i] is the cost of running the i-th company, and amount[i] is the maximal amount of data that the i-th company can process.

Also you will be given two companies - company1 and company2. The company company1 has an infinite amount of unprocessed data in its supply which can be processed. Your goal is to convert as much data as possible to the new format of company2, spending the least amount of money as possible. You are to select the companies you want to run, since only running companies can process the data. Return the names of those companies as a String[], sorted in lexicographical order. If more than one answer is possible, return the lexicographically smallest one. If there is no way company2 can process any data at all, return an empty String[].

 

Definition

    
Class:SoftwareCompanies
Method:produceData
Parameters:String[], String[], int[], int[], String, String
Returns:String[]
Method signature:String[] produceData(String[] names, String[] process, int[] cost, int[] amount, String company1, String company2)
(be sure your method is public)
    
 

Notes

-String A is lexicographically smaller than string B if it contains a smaller letter at the first position they differ or if A is a prefix of B. List A is lexicographically smaller than list B if it contains a lexicographically smaller string at the first position they differ or if it is a prefix of list B.
 

Constraints

-names will contain between 2 and 12 elements, inclusive.
-Each element of names will contain between 1 and 50 lowercase letters ('a'-'z'), inclusive.
-All elements of names will be distinct.
-amount, cost, process and names will all contain same number of elements.
-Each element of process will contain between 0 and 50 characters, inclusive.
-Each element of process will contain a single-space separated names of companies without any leading or trailing spaces.
-Each element of process will contain no duplicate names.
-Each element of process will list only companies presented in names.
-Element i of process will not contain the i-th company in names.
-Each element of cost will be between 0 and 1000000, inclusive.
-Each element of amount will be between 1 and 1000000, inclusive.
-company1 and company2 will both be present in names.
-company1 and company2 will be distinct.
 

Examples

0)
    
{"topcoder", "doodle", "nasa", "ninny", "idm", "noname", "kintel"}
{"doodle nasa noname", "idm ninny noname", "idm ninny noname", "kintel", "kintel", "", ""}
{1, 2, 7, 4, 6, 1, 2}
{50, 10, 11, 9, 14, 11, 23}
"topcoder"
"kintel"
Returns: {"doodle", "idm", "kintel", "nasa", "ninny", "topcoder" }
topcoder has an unlimited amount of data. We take 21 units of topcoder data, with 10 units going to doodle and 11 to nasa. When doodle processes all 10 units, all 10 units of the output go to idm, and, after being processed by idm, those 10 units continue to kintel. 11 units of data processed by nasa are split between ninny (9 units) and idm (2 units). Both those companies give their output to kintel, which has enough power to process all 21 units of data it gets. Therefore the optimal strategy is to run all the companies except "noname".
1)
    
{"b", "bz", "ba", "d", "z", "ca", "y", "a", "x"}
{"bz ba z ca", "ba", "d", "", "ca", "d", "a", "x", ""}
{5, 5, 5, 10, 6, 6, 3, 0, 3}
{10, 7, 10, 9, 6, 9, 23, 13, 11}
"b"
"d"
Returns: {"a", "b", "ba", "d" }
2)
    
{"b", "bz", "ba", "d", "z", "ca", "y", "a", "x"}
{"bz ba z ca", "ba", "d", "", "ca", "d", "a", "x", ""}
{5, 5, 5, 10, 6, 6, 3, 1, 3}
{10, 7, 10, 9, 6, 9, 23, 13, 11}
"b"
"d"
Returns: {"b", "ba", "d" }
3)
    
{"coma", "comb", "comc", "comd"}
{"comb", "coma", "comd", "comc"}
{10, 54, 18, 93}
{10, 10, 10, 10}
"comb"
"comc"
Returns: { }
4)
    
{"c", "b", "a"}
{"b", "c", ""}
{1, 1, 0}
{1, 1, 22}
"c"
"b"
Returns: {"a", "b", "c" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TristripeBacteria

Search



Used in:

TCCC07 Round 3

Used as:

Division I Level Two

Writer:

Mike Mirzayanov

Testers:

PabloGilberto , radeye , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8150

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10908&pm=8150

Problem Statement

    

You are given a String[] photo containing a photograph of some bacteria. The bacteria lie in a rectangular grid, and the j-th character of the i-th element of photo represents the content of the cell at row i, column j of the grid. The '.' character represents empty space and the '*' character represents a part of a bacterium. Two non-empty cells a and b belong to the same bacterium if and only if there exists a chain of cells where the first cell is a, the last cell is b, and each pair of consecutive cells in the chain shares a common side.

You are studying a special kind of bacteria called tristripe bacteria. They have a special property: a tristripe bacterium can be formed by exactly three stripes (horizontal or vertical) that possibly intersect and/or overlap. All four bacteria in the picture below are tristripe:

{"........................***...",
 "......*........*.........***..",
 "...******..................***",
 "......*.............*.........",
 ".....**.........******........",
 ".............................."}

Return the number of tristripes in the photo.

 

Definition

    
Class:TristripeBacteria
Method:howMany
Parameters:String[]
Returns:int
Method signature:int howMany(String[] photo)
(be sure your method is public)
    
 

Constraints

-photo will contain between 1 and 50 elements, inclusive.
-Each element of photo will contain between 1 and 50 characters, inclusive.
-Each element of photo will contain the same number of characters.
-Each element of photo will contain only the characters '.' and '*'.
 

Examples

0)
    
{"........................***...",
 "......*........*.........***..",
 "...******..................***",
 "......*.............*.........",
 ".....**.........******........",
 ".............................."}
Returns: 4
This example is from the statement.
1)
    
{".....................*********",
 "......*..............*********",
 "...******............*********",
 "......*.........*...*.........",
 ".....**.........******........",
 "....**........................"}
Returns: 2
The leftmost bacterium is not a tristripe.
2)
    
{"."}
Returns: 0
3)
    
{"*****************"}
Returns: 1
4)
    
{"*","*","*","*","*","*","*"}
Returns: 1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MyFriends

Graph Theory, Greedy, Math



Used in:

SRM 398

Used as:

Division I Level Three

Writer:

boba5551

Testers:

PabloGilberto , legakis , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8144

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12170&pm=8144

Problem Statement

    

There is a group of n kids, numbered 0 through n-1, where n is an odd number. Each kid has some friends within the group, and each kid knows how many friends each of the other kids has. Friendship is symmetric, so if kid 0 is a friend of kid 1, then kid 1 is a friend of kid 0. Each kid i also supports exactly one other kid (i+k) % n, not necessarily a friend.



You ask each kid to answer the following question: Consider each kid in the group except yourself and the kid you support. What is the sum of the number of friends each of them has? For example, if you ask kid 0 this question, and kid 0 supports kid 1, he should tell you (the number of friends kid 2 has) + (the number of friends kid 3 has) + ... + (the number of friends kid n-1 has).



You are given a int[] sumFriends, where the i-th element (0-indexed) is the answer given to you by kid i. Some of the kids might not be telling the truth (they are just kids, forgive them). Return "IMPOSSIBLE" if it is impossible for all the given answers to be accurate. Otherwise, return "POSSIBLE" (all quotes for clarity).

 

Definition

    
Class:MyFriends
Method:calcFriends
Parameters:int[], int
Returns:String
Method signature:String calcFriends(int[] sumFriends, int k)
(be sure your method is public)
    
 

Constraints

-sumFriends will contain odd number of elements.
-sumFriends will contain between 3 and 49 elements, inclusive.
-Each element of sumFriends will be between 0 and 9999, inclusive.
-k will be between 1 and (number of elements in sumFriends)-1, inclusive.
 

Examples

0)
    
{8, 9, 8, 8, 9}
2
Returns: "POSSIBLE"
We can get such sums only if kid 1 has 2 friends and all other kids have 3 friends. Such a situation is possible. For example:
Kid             His/her friends
0               1, 3, 4
1               0, 2
2               1, 3, 4
3               0, 2, 4
4               0, 2, 3
1)
    
{7, 6, 5, 4, 4}
2
Returns: "IMPOSSIBLE"
2)
    
{5, 6, 5, 4, 4}
1
Returns: "POSSIBLE"
3)
    
{1, 2, 3}
1
Returns: "IMPOSSIBLE"
Here kid 2 supports kid 0, so he tells us the number of friends of kid 1. But it's obviously impossible for kid 1 to have 3 friends.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RangeFixer

Search



Used in:

TCHS SRM 39

Used as:

Division I Level Three

Writer:

jbernadas

Testers:

PabloGilberto , brett1479 , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8120

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10782&pm=8120

Problem Statement

    

Given a int[] values, return a int[] of the same size where the k-th element is an integer X such that low <= X <= high and the bit difference between X and values[k] is minimal. If there are multiple such int[]s, return the one that comes first lexicographically. A int[] a1 comes before a int[] a2 lexicographically if a1 has a lower value at the first position where they differ.



To calculate the bit difference between two integers, first convert them to their binary representations. If their binary representations have different lengths, pad the shorter one with 0's on the left until they both have the same length. The bit difference is the number of positions where the two binary representations differ.

 

Definition

    
Class:RangeFixer
Method:closestValue
Parameters:int, int, int[]
Returns:int[]
Method signature:int[] closestValue(int low, int high, int[] values)
(be sure your method is public)
    
 

Constraints

-low will be between 0 and 2^30 - 1, inclusive.
-high will be between low and 2^30 - 1, inclusive.
-values will contain between 1 and 50 elements, inclusive.

-Each element of values will be between 0 and 2^30 - 1, inclusive.
 

Examples

0)
    
101
105
{71}
Returns: {103 }
1)
    
98
304
{12, 65, 302, 1, 1000000}
Returns: {140, 193, 302, 129, 192 }
2)
    
16
16
{1000000}
Returns: {16 }
There is only one value in the interval, so there is only one possible answer.
3)
    
83
92
{48}
Returns: {84 }
The bit difference between 48 and 84 is 3 and the bit difference between 48 and 88 is 3 too, so we return the lowest one.
4)
    
1
4
{5, 6, 7}
Returns: {1, 2, 3 }
5)
    
10000000
20000000
{50382, 1234, 58126, 13952, 1475, 24, 1560}
Returns: {16827598, 16778450, 16835342, 16791168, 16778691, 16777240, 16778776 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Secretary

Sorting, String Manipulation



Used in:

TCHS SRM 40

Used as:

Division I Level One

Writer:

StevieT

Testers:

PabloGilberto , brett1479 , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8055

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10784&pm=8055

Problem Statement

    You recently asked your secretary to put some box files into storage for you. He was supposed to sort them with the names of the files in lexicographical order, but an error with the printer caused the names to be printed with the characters in reverse order and he sorted them based on the printed names. You want to know what order the files ended up in.



You will be given the original names of the files in a String[] files. Return a String containing the original name of the first file in the order your secretary sorted them.
 

Definition

    
Class:Secretary
Method:wrongOrdering
Parameters:String[]
Returns:String
Method signature:String wrongOrdering(String[] files)
(be sure your method is public)
    
 

Constraints

-files will contain between 1 and 50 elements, inclusive.
-Each element of files will contain between 1 and 50 characters, inclusive.
-files will contain only uppercase letters ('A'-'Z').
 

Examples

0)
    
{"JAMES","PETER","ADAM","JOHN","DAVE","EDWARD"}
Returns: "EDWARD"
These are your employee records that the secretary is sorting. The order in which your secretary sorted them is:



DRAWDE - EDWARD

EVAD - DAVE

MADA - ADAM

NHOJ - JOHN

RETEP - PETER

SEMAJ - JAMES



"EDWARD" is the first file in the list.
1)
    
{"ALGORITHM","DESIGN","DEVELOPMENT","TCHS","STUDIO","MARATHON"}
Returns: "ALGORITHM"
2)
    
{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P"}
Returns: "A"
3)
    
{"ACCOUNTING"
,"MARKETING"
,"PERSONNEL"
,"FINANCE"
,"SALES"
,"ADMINISTRATION"
,"IT"
,"MANAGEMENT"
,"OPERATIONS"
,"LEGAL"
,"PURCHASING"
,"LOGISTICS"
,"TRAINING"
,"TECHNICAL"}
Returns: "FINANCE"
4)
    
{"AAAAA","AA","AAA"}
Returns: "AA"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SongsList

Greedy, Simple Search, Iteration



Used in:

TCCC07 Semi 2

Used as:

Division I Level One

Writer:

ivan_metelsky

Testers:

PabloGilberto , vorthys , Olexiy , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8049

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10957&pm=8049

Problem Statement

    

You are given a String[] songs, each element of which represents one song and has the format "BAND ALBUM SONG" (quotes for clarity), where BAND, ALBUM and SONG are non-empty strings of lowercase letters, representing the band name, the album name and the song name, respectively.

You wish to arrange all the songs into a list sorted in lexicographical order. Each song can be included in the list in one of the following 6 formats: "BAND ALBUM SONG", "BAND SONG ALBUM", "ALBUM BAND SONG", "ALBUM SONG BAND", "SONG BAND ALBUM", "SONG ALBUM BAND". Different songs in the list can have different formats. In other words, the format chosen for a song does not depend on the formats chosen for other songs in the list. Determine all possible 0-indexed positions of the song represented by songs[0] in the list. Return a int[] containing all the distinct positions in ascending order.

 

Definition

    
Class:SongsList
Method:getPositions
Parameters:String[]
Returns:int[]
Method signature:int[] getPositions(String[] songs)
(be sure your method is public)
    
 

Notes

-A String A comes before a String B lexicographically if A is a proper prefix of B, or if A has a smaller character at the first position where the characters differ. Note that the space character (' ') is lexicographically smaller than the letters 'A'-'Z'.
 

Constraints

-songs will contain between 1 and 50 elements, inclusive.
-Each element of songs will contain between 5 and 50 characters, inclusive.
-Each element of songs will be in the format "BAND ALBUM SONG" (quotes for clarity), where BAND, ALBUM and SONG are non-empty sequences of lowercase letters ('a'-'z').
-The following property will hold for every pair of distinct songs S1 and S2 in songs: Write S1 in all 6 possible formats. Then, write S2 in all 6 possible formats. There will be no overlap between these two lists (overlap within each list is permitted). For example, songs cannot contain both "a b c" and "c b a" because "c b a" can be written as "a b c" (in "SONG ALBUM BAND" format).
 

Examples

0)
    
{ "beatles help yesterday",
  "queen innuendo showmustgoon",
  "eagles hotelcalifornia hotelcalifornia" }
Returns: {0, 1, 2 }

If we write all the songs in the format "BAND ALBUM SONG", then the song from songs[0] will get position 0 and the list will be the following:



"beatles help yesterday"
"eagles hotelcalifornia hotelcalifornia"
"queen innuendo showmustgoon"

If we want to put "yesterday" in position 1, we can write it in the format "ALBUM BAND SONG" to get the following list:



"eagles hotelcalifornia hotelcalifornia"
"help beatles yesterday"
"queen innuendo showmustgoon"

And if we want to put "yesterday" in position 2, we can write it in the format "SONG BAND ALBUM" to get the following list:



"eagles hotelcalifornia hotelcalifornia"
"queen innuendo showmustgoon"
"yesterday beatles help"
1)
    
{ "a a a",
  "b b b",
  "c c c" }
Returns: {0 }
2)
    
{ "b e h",
  "i i i",
  "g g g",
  "f f f",
  "d d d",
  "c c c",
  "a a a" }
Returns: {1, 3, 5 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BinaryPowerBishop

Brute Force, Greedy



Used in:

TCCC07 Semi 3

Used as:

Division I Level Three

Writer:

ivan_metelsky

Testers:

PabloGilberto , vorthys , Olexiy , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8030

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10958&pm=8030

Problem Statement

    

A binary power bishop is at point (0, 0) and wants to get to point (finishX, finishY). In one move, the bishop can go from point (x, y) to any one of the following points: (x + 2k, y + 2k), (x + 2k, y - 2k), (x - 2k, y + 2k), (x - 2k, y - 2k), where k is any non-negative integer. The only restriction on the bishop's moves is that all of them must have distinct values of k.

Return a String[] describing the path of the bishop from (0, 0) to (finishX, finishY) that contains the minimum possible number of moves. The elements of the return should describe all the points visited by the bishop, in order, including the start and end points. Each element should describe a single point (x, y) in the format "x,y" (quotes for clarity). If there are multiple possible return values, return the one that comes first lexicographically. If it is impossible to reach the finish point, return an empty String[] instead.

 

Definition

    
Class:BinaryPowerBishop
Method:getPath
Parameters:int, int
Returns:String[]
Method signature:String[] getPath(int finishX, int finishY)
(be sure your method is public)
    
 

Notes

-A String[] A comes before a String B lexicographically if A has a lexicographically smaller String at the first index at which they differ. A String A comes before a String B lexicographically if A is a proper prefix of B, or if A has a smaller character at the first position where the strings differ. When comparing the characters, refer to the following list of characters in ascending order: ',', '-', '0', '1', ..., '9'.
 

Constraints

-finishX and finishY will each be between 1 and 100000000, inclusive.
 

Examples

0)
    
16
16
Returns: {"0,0", "16,16" }
Only one move is needed.
1)
    
8
24
Returns: {"0,0", "-8,8", "8,24" }
Here two moves is enough. Note that the bishop can visit points with negative coordinates.
2)
    
11
22
Returns: { }
If the bishop moves from (x1, y1) to (x2, y2), the parities of the sums x1+y1 and x2+y2 are the same. Therefore, the bishop can't visit any point (x, y) with an odd sum x+y.
3)
    
123
321
Returns: 
{"0,0",
"-128,128",
"-112,112",
"-104,104",
"-100,100",
"-102,98",
"-101,97",
"-133,65",
"123,321" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WeighingScale

Graph Theory, Search



Used in:

SRM 361

Used as:

Division I Level Three

Writer:

slex

Testers:

PabloGilberto , Yarin , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8025

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10773&pm=8025

Problem Statement

    

Little George has found an old-fashioned balance scale and a set of weights in the attic. The scale has two weighing pans and it allows you to check if the content of the left pan is heavier, lighter, or the same weight as the content of the right pan. The box where the weights were kept says that each of them weigh 10, 20, or 30 grams, but the faded paint makes it impossible to tell which is which.

George started playing with the scale by comparing one weight against another, and noting down all his results. After a while he got bored with that, and came up with a new experiment. He put the A-th and B-th weights on the left pan and tried to guess what would happen when he put another two weights on the right pan.

You are given a String[] measures with the results of the previous experiments. The j-th character of the i-th element represents the result of comparing the i-th weight against the j-th weight, and it can have one of four values:

  • '+' - the i-th weight is heavier than the j-th weight.
  • '-' - the i-th weight is lighter than the j-th weight.
  • '=' - both weights have the same weight.
  • '?' - the two weights weren't compared.
Return a int[] containing exactly three integers in the following order: the number of different pairs of weights you can put on the right pan to make it lighter than the left pan, the number of pairs to make both pans the same weight, and the number of pairs to make the left pan lighter. Two pairs of weights are different if one pair contains at least one weight with an index that's not contained in the other pair. You should only consider the pairs that make the result unambiguously predictable based on the results in measures.

 

Definition

    
Class:WeighingScale
Method:count
Parameters:String[], int, int
Returns:int[]
Method signature:int[] count(String[] measures, int A, int B)
(be sure your method is public)
    
 

Notes

-Since the weights with indices A and B are already on the left pan you should only consider pairs that contain neither A nor B for the right pan.
 

Constraints

-measures will contain between 4 and 50 elements, inclusive.
-Each element of measures will contain exactly N characters, where N is the number of elements in measures.
-Each element of measures will contain only '+','-', '=', or '?'.
-The i-th character of the i-th element of measures will be '?'
-If the j-th character of the i-th element of measures is '+' than the i-th character of the j-th element will be '-' and vice versa.
-If the j-th character of the i-th element of measures is '=' or '?' than the i-th character of the j-th element will be the same.
-There will exist at least one way to assign values to the weights that will match the results in measures.
-A will be between 0 and N-1, inclusive, where N is the number of elements in measures.
-B will be between 0 and N-1, inclusive, where N is the number of elements in measures.
-A will be different than B.
 

Examples

0)
    
{"?+????","-?+???","?-????","????+?", "???-?+","????-?"}
1
4
Returns: {1, 4, 1 }
We have the following weight relations:
w0 > w1 > w2
w3 > w4 > w5
It can only be true if the values are (30,20,10,30,20,10). The left pan contains weights 1 and 4 with total weight 20+20=40. There is one pair (0,3) heavier than that, one pair (2,5) lighter than that and the remaining four pairs have the same weight.
1)
    
{"?+?????","-?+????","?-?????","????+??", "???-?+?","????-??", "???????"}
0
3
Returns: {10, 0, 0 }
The first six weights are the same as in example 0 (30,20,10,30,20,10). We know nothing about the 7th weight, but still, putting the two 30 gram weights on the left pan assures that it will be heavier than any other pair.
2)
    
{"?+?????","-?+????","?-?????","????+??", "???-?+?","????-??", "???????"}
1
4
Returns: {1, 4, 1 }
With the same measures as in the previous example, now weights 1 and 4 lie on the left pan, for a total weight of 40. We can predict what will happen only if the pair on the right pan doesn't contain the 7th weight; otherwise it's impossible to tell.
3)
    
{"??+?", "???+", "-???", "?-??"}
0
1
Returns: {1, 0, 0 }
We know that w0 > w2 and w1 > w3 thus w0+w1 must be heavier than w2+w3.
4)
    
{"??+??", "???+?", "-???=", "?-???", "??=??"}
0
1
Returns: {3, 0, 0 }
5)
    
{"?+???++?????++","-??=?=???????=","??????????=???","?=??+?==??????",
"???-???-???-??","-=????????????","-??=???=?-+???","???=+?=???????",
"??????????????","??????+???????","??=???-????-??","????+?????+???",
"-?????????????","-=????????????"}
6
2
Returns: {1, 10, 36 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ImageReconstruction

Brute Force, Math, Search



Used in:

MM 20

Used as:

Division I Level One

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8024

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10860&pm=8024

Problem Statement

    

Your job is to unscramble a photograph in the fewest number of iterations possible.

The image is divided up into uniformly-sized square pieces and the pieces are shuffled. Your method will be provided with the size of each piece in pixels (the width and height are the same), the number of columns and rows of pieces in the image, and an array of pixel values. Each pixel value is encoded as an integer with eight bits per color component in RGB order, from most significant to least significant. You can decode each pixel with int red = (pixel >> 16), green = (pixel >> 8) & 0xff, blue = pixel & 0xff;.

Pieces are numbered from zero to rows*columns-1. Given a piece n, the image data for that piece can be found in row-major order in the pixels array starting at n*pieceSize*pieceSize. You can extract the pixel value at line y and column x of piece n with the expression pixels[n*pieceSize*pieceSize+y*pieceSize+x].

You are provided with a verify method which tells you which pieces are in the correct places in a guess. You pass it an array containing rows*columns integers, each of which represents a slot in the image in row major order so that the guess for the slot at row r and column c is at r*columns+c. Each slot should contain a piece number as described above. The method returns a corresponding array of integers. If the guess for a particular slot is correct, the corresponding return slot will be 1; otherwise, it will be 0. This means that it is possible to create the correct image without looking at the pixel data.

Your solution must return a guess in the same format as would be passed to the verify method. Your raw score for each case will be 1 plus the number of calls made to verify, or zero if your solution does not return the pieces in the correct order. Your aggregated score will be the sum of the lowest raw score received by any competitor on a case divided by your score on the case, excluding any cases in which you received a raw zero.

Visualizer

As in past contests, we have provided a Java visualization tool .
 

Definition

    
Class:ImageReconstruction
Method:reconstruct
Parameters:int, int, int, int[]
Returns:int[]
Method signature:int[] reconstruct(int pieceSize, int columns, int rows, int[] pixels)
(be sure your method is public)
    
 

Notes

-You have 60 seconds per case.
-You can use a maximum of 512M of memory.
-Test cases are chosen using http://commons.wikimedia.org/wiki/Special:Random/Image . Images which are not primarily photographic or photo-realistic, such as line drawings, are discarded.
-Images are centered and cropped after any scaling to make each image dimension a multiple of the piece size.
-As is customary, row (or line) 0 is the top.
-verify does not require each slot to be filled with a unique piece number. You can pass all zeros, for example.
 

Constraints

-pieceSize will be 10, 20, or 30, chosen uniformly at random
-neither image dimension will be more than 500 pixels - larger images will be scaled so that the larger dimension becomes 500
 

Examples

0)
    
"e1,http://commons.wikimedia.org/wiki/Image:Chemical_Brothers_Live.jpg,20,25,18,23784"
Returns: 
"   Image URL: http://commons.wikimedia.org/wiki/Image:Chemical_Brothers_Live.jpg
  Piece Size: 20x20
     Columns: 25
        Rows: 18
        Seed: 23784

"
1)
    
"e2,http://commons.wikimedia.org/wiki/Image:Flickr_hellochris_202508906--In-N-Out_triple_cheeseburger_fries.jpg,30,16,12,27360"
Returns: 
"   Image URL: http://commons.wikimedia.org/wiki/Image:Flickr_hellochris_202508906--In-N-Out_triple_cheeseburger_fries.jpg
  Piece Size: 30x30
     Columns: 16
        Rows: 12
        Seed: 27360

"
2)
    
"e3,http://commons.wikimedia.org/wiki/Image:Tienen_Stadhuis.jpg,30,16,11,9981"
Returns: 
"   Image URL: http://commons.wikimedia.org/wiki/Image:Tienen_Stadhuis.jpg
  Piece Size: 30x30
     Columns: 16
        Rows: 11
        Seed: 9981

"
3)
    
"e4,http://commons.wikimedia.org/wiki/Image:Todaiji05s3200.jpg,30,11,16,6231"
Returns: 
"   Image URL: http://commons.wikimedia.org/wiki/Image:Todaiji05s3200.jpg
  Piece Size: 30x30
     Columns: 11
        Rows: 16
        Seed: 6231

"
4)
    
"e5,http://commons.wikimedia.org/wiki/Image:800px-Kalithea_Achaias.jpg,20,24,15,20710"
Returns: 
"   Image URL: http://commons.wikimedia.org/wiki/Image:800px-Kalithea_Achaias.jpg
  Piece Size: 20x20
     Columns: 24
        Rows: 15
        Seed: 20710

"
5)
    
"e6,http://commons.wikimedia.org/wiki/Image:Passower_Kirche.JPG,30,16,12,32464"
Returns: 
"   Image URL: http://commons.wikimedia.org/wiki/Image:Passower_Kirche.JPG
  Piece Size: 30x30
     Columns: 16
        Rows: 12
        Seed: 32464

"
6)
    
"e7,http://commons.wikimedia.org/wiki/Image:Wawer.jpg,30,12,16,10059"
Returns: 
"   Image URL: http://commons.wikimedia.org/wiki/Image:Wawer.jpg
  Piece Size: 30x30
     Columns: 12
        Rows: 16
        Seed: 10059

"
7)
    
"e8,http://commons.wikimedia.org/wiki/Image:Eisenbahnmarkthalle5_Detail_Berlin.JPG,10,32,50,21813"
Returns: 
"   Image URL: http://commons.wikimedia.org/wiki/Image:Eisenbahnmarkthalle5_Detail_Berlin.JPG
  Piece Size: 10x10
     Columns: 32
        Rows: 50
        Seed: 21813

"
8)
    
"e9,http://commons.wikimedia.org/wiki/Image:Teplice%2C_Prosetice%2C_14Tr_III.JPG,20,25,16,23572"
Returns: 
"   Image URL: http://commons.wikimedia.org/wiki/Image:Teplice%2C_Prosetice%2C_14Tr_III.JPG
  Piece Size: 20x20
     Columns: 25
        Rows: 16
        Seed: 23572

"
9)
    
"e10,http://commons.wikimedia.org/wiki/Image:Woody_London.jpg,20,24,15,26240"
Returns: 
"   Image URL: http://commons.wikimedia.org/wiki/Image:Woody_London.jpg
  Piece Size: 20x20
     Columns: 24
        Rows: 15
        Seed: 26240

"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CoolRectangles

Geometry, Graph Theory, Greedy, Math



Used in:

SRM 362

Used as:

Division I Level Three

Writer:

eleusive

Testers:

PabloGilberto , Olexiy , lovro , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8015

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10775&pm=8015

Problem Statement

    You're given several rectangles in the cartesian plane with sides parallel to the coordinate axes. A "cool rectangle" is a rectangle in the plane such that each of its edges completely lies on the edges of some input rectangles (these edges may overlap). You want to "compress" the input rectangles by shrinking them into cool rectangles (this will happen instantaneously).



To compress an input rectangle into a cool rectangle, the interior of the cool rectangle must be completely contained within the input rectangle. The interiors of the chosen cool rectangles must not overlap (though their edges may touch), and each cool rectangle may compress at most one input rectangle. Determine the smallest total area of cool rectangles required to shrink all the input rectangles, or return -1 if it is impossible.



The input rectangles will be described by int[]s x1, y1, x2, and y2, where (x1[i],y1[i]) and (x2[i],y2[i]) are opposite corners of the ith rectangle.
 

Definition

    
Class:CoolRectangles
Method:compress
Parameters:int[], int[], int[], int[]
Returns:int
Method signature:int compress(int[] x1, int[] y1, int[] x2, int[] y2)
(be sure your method is public)
    
 

Constraints

-x1 will contain between 1 and 30 elements, inclusive.
-x1, y1, x2, and y2 will contain the same number of elements.
-Each element of x1, y1, x2, and y2 will be between -10000 and 10000, inclusive.
-For each rectangle, x1[i] < x2[i], and y1[i] < y2[i].
 

Examples

0)
    
{0,1,2}
{0,1,2}
{1,2,3}
{1,2,3}
Returns: 3
We have three non-overlapping squares, so the only cool rectangles are the input rectangles.
1)
    
{0,1}
{0,1}
{2,3}
{2,3}
Returns: -1
The overlapping squares generate 3 cool rectangles. However, there is no way to choose 2 non-overlapping cool rectangles to use.
2)
    
{1,0}
{1,2}
{3,4}
{4,3}
Returns: 3
These rectangles intersect in a way that allows for cool rectangles of area 1 and 2 to be used (although there are 11 available cool rectangles).
3)
    
{0,1,1}
{0,1,1}
{2,3,2}
{2,3,2}
Returns: -1
4)
    
{0,-1,-2,-3}
{0,1,2,3}
{1,2,3,4}
{7,6,5,4}
Returns: 4
5)
    
{1011,-647,134,-2009,875,819}
{189,-1504,1830,-1383,-319,825}
{2530,1930,620,-805,1821,1054}
{1419,1224,2476,203,1982,2943}
Returns: 2325650

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GameOfEight

Graph Theory, Simple Search, Iteration



Used in:

TC China 08 - 1E

Used as:

Division I Level Three

Writer:

mateuszek

Testers:

PabloGilberto , Olexiy , Mike Mirzayanov , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7995

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13677&pm=7995

Problem Statement

    

In "The Game of Eight", you are given a 3x3 board containing 8 squares labelled 1 through 8, and one empty space. The initial state of the board is given in the String[] board, where '.' represents the empty space. In each turn, you pick any square which is horizontally or vertically adjacent to an empty space and move it to the empty space (see example 0 for clarification). Your goal is to arrange the squares so the board looks like this:

{"123",
 "456",
 "78."}

Return the minimum number of moves necessary to achieve this goal, or -1 if it's impossible.

 

Definition

    
Class:GameOfEight
Method:fewestMoves
Parameters:String[]
Returns:int
Method signature:int fewestMoves(String[] board)
(be sure your method is public)
    
 

Constraints

-board will contain exactly 3 elements.
-Each element of board will contain exactly 3 characters.
-Each character of each element of board will be a digit ('1' - '8') or a dot ('.').
-Each number between 1 and 8 will appear exactly once on the board.
 

Examples

0)
    
{"123",
 "485",
 "76."}
Returns: 4
The optimal solution is the following:



123       123       123       123       123
485  -->  485  -->  4.5  -->  45.  -->  456
76.       7.6       786       786       78.
1)
    
{"123",
 "456",
 "78."}
Returns: 0
The game is already completed.
2)
    
{".23",
 "456",
 "781"}
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

JohnnysPhone

Dynamic Programming, String Manipulation



Used in:

SRM 370

Used as:

Division II Level Three

Writer:

mateuszek

Testers:

PabloGilberto , Olexiy , lovro , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7967

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10786&pm=7967

Problem Statement

    Little Johnny loves sending text messages to his friends. Recently, he bought himself a cool new phone (an Eric-Sonnicson F198-EX32 with MP3 player, GPS navigation, built-in washing machine, and many other features). Johnny's favorite feature is a T9 dictionary that simplifies typing. Here's how T9 works. The 26 letters of the alphabet are assigned to the phone's keypad as follows:
  • 2 - a, b, c
  • 3 - d, e, f
  • 4 - g, h, i
  • 5 - j, k, l
  • 6 - m, n, o
  • 7 - p, q, r, s
  • 8 - t, u, v
  • 9 - w, x, y, z
The phone also has three special buttons: "Next in dictionary", "New word" and "Space". These are described in the following paragraphs.



To type a word, you press the digit buttons corresponding to the letters in the word one by one. Each time you press a digit button, the T9 feature will automatically find the first word in the dictionary that has a prefix matching the digits you've typed so far. It will then display that prefix. For example, if the dictionary is { "bad", "apple" }, and you press the 2 button, the display will read "b" since "bad" is the first word with a prefix of "a", "b" or "c". If there are multiple words in the dictionary that have a matching prefix, you can press the "Next in dictionary" button to display the next prefix. In this example, pressing "Next in dictionary" will cause the display to change to "a" since "apple" is the next word with a matching prefix (note that dictionary entries are not necessarily in alphabetical order). However, if you then type another 2, the display will read "ba" since "bad" is the only word that matches that prefix. If there are no matches in the dictionary for what you've typed so far, nothing will be displayed. Also, if you press "Next in dictionary" more times than there are words with the prefix you typed, nothing will be displayed. If you type something and press "Next in dictionary" one or more times after that, when you type the rest of the word, T9 will search the dictionary from the place it has finished for the last prefix. (See examples for more clarification.)



To start a new word, you can press the "Space" button, which will insert a space and let you start typing a new word. Alternatively, you can use the unusual "New word" button, which lets you start a new word without inserting a space, leaving the previous word in whatever state it was in. For example, using the above dictionary, you can press 2, then "New word", then 2, and then 7 to type "bap", a word that does not exist in the dictionary. You can also sometimes use this method to type words that are in the dictionary using fewer button presses. Each time you start typing a new word, T9 will search the dictionary from the beginning.



You are given a String[] dictionary. Concatenate the elements of dictionary into a single string. This string will be a space separated list of words in the order that they appear in the dictionary. You will be also given a String message, the message that Johhny wants to type. Return the minimum possible number of button presses required to type the message, or -1 if it is impossible to type the message using the given dictionary.
 

Definition

    
Class:JohnnysPhone
Method:minimizePushes
Parameters:String[], String
Returns:int
Method signature:int minimizePushes(String[] dictionary, String message)
(be sure your method is public)
    
 

Constraints

-dictionary will contain between 1 and 50 elements, inclusive.
-Each element of dictionary will contain between 1 and 50 characters, inclusive.
-Each element of dictionary will contain only lowercase letters ('a'-'z') and spaces (' ').
-dictionary, when concatenated, will be a single space separated list of words, without leading or trailing spaces.
-message will contain between 1 and 50 characters, inclusive.
-message will contain only lowercase letters ('a'-'z') and spaces (' ').
 

Examples

0)
    
{ "age messagd messagd message" }
"message"
Returns: 8
The most obvious way to type "message" is to type the seven digits corresponding to the letters in order: 6, 3, 7, 7, 2, 4, 3. At this point, the display will read "messagd" since that is the first matching prefix in the dictionary. You would then have to press "Next in dictionary" two times to get to "message". That's a total of 9 button presses.



A faster way to type "message" is to first type the digits 6, 3, 7, 7. The display will read "mess". Now, press "New word" to start a new word without inserting a space. Type the digits 2, 4, 3. "age" is the only matching prefix in the dictionary for this second word, so the display will read "message". That only requires 8 button presses.
1)
    
{ "b a c d" }
"abcd  dcba "
Returns: 23
2)
    
{ "a b c" }
"d"
Returns: -1
3)
    
{ "gajdkwifpcks iclfabc" }
"gajf"
Returns: -1
The digits corresponding to the letters in "gajf" are 4, 2, 5, 3. If we type the first three digits, the display will read "gaj". At this point, there's no way to get "f" as the next letter. If we type 3, the display will change to "gajd". If we then press "Next in dictionary", it will change to "iclf". "gajf" is impossible to type with the given dictionary.
4)
    
{"a ", "aa ", "aaa ", "aaaa ", "ab"}
"ab"
Returns: 5
5)
    
{ "aaa ", "bbb ", "ccc" }
"ccc"
Returns: 5
When we type 2, the display will read "a". Now we can press "Next in dictionary" two times and the display will read "c". Now we should just press 2 two more times to finish our message. Note, that when we're finishing the message, the T9 doesn't search the dictionary from the beginning but stays where it were before (unless we press "New word").

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

EscapeArtist

Brute Force, Dynamic Programming, Graph Theory, Math, Recursion, Search



Used in:

SRM 386

Used as:

Division I Level Three

Writer:

eleusive

Testers:

PabloGilberto , Olexiy , lovro , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7953

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11120&pm=7953

Problem Statement

    You're trapped inside a facility that contains several rooms connected by corridors. You're currently located in room start and you wish to reach the finish using the least amount of time as possible. Each corridor takes one second to travel through.



Your task is complicated by the fact that there are several agents located in various rooms. These agents wish to capture you, but each one has a particular destination, as they each have different intelligence suggesting that you will head towards their destination. Like yourself, these agents will also reach their target room in the least possible amount of time. The agents begin moving at the same time as you do. If there are multiple shortest paths that an agent may use, you may assume each such path is equally likely as his choice. Once an agent reaches his goal, he will stay there indefinitely. Note that while you are aware of each agent's start and target rooms, you will be unaware of the agent's movements as you move through the facility.



As you wish to dodge capture as well as reach the exit as quickly as possible, you will use the following strategy. Each second you choose the way which allows you to reach the exit as quickly as possible (see example 6 for clarification). If there are multiple ways to do so, you choose the corridor that minimizes the probability of being captured from that point on. As soon as you reach the exit room, you leave the facility and cannot be captured. However, you may be captured the moment that you reach the exit room (see example 7).



There are two ways that you can be captured by an agent.

1) You travel through a corridor at the same time an agent does (you can be traversing the corridor in either the same direction or the opposite direction).

2) You're in a room at the same time as an agent.



The facility is described by a String[] corridors. The jth character of the ith element of corridors will be a '1' if there is a corridor between rooms i and j, and '0' otherwise. Each element of agentStart and agentTarget represents the start and target rooms, respectively, of an agent.



Given this information, return the probability that you will be captured by an agent if you follow the described strategy.



 

Definition

    
Class:EscapeArtist
Method:bestRoute
Parameters:String[], int[], int[], int, int
Returns:double
Method signature:double bestRoute(String[] corridors, int[] agentStart, int[] agentTarget, int start, int finish)
(be sure your method is public)
    
 

Notes

-The returned value must be accurate to within a relative or absolute value of 1E-9.
 

Constraints

-corridors will contain between 2 and 25 elements, inclusive.
-Each element of corridors will contain exactly N characters, where N is the number of elements in corridors.
-Each character in corridors will be either a '0' (zero) or '1' (one).
-The jth character of the ith element of corridors will be the same as the ith character of the jth element of corridors.
-The ith character of the ith element of corridors will be '0'.
-start and finish will each be between 0 and N-1, inclusive, where N is the number of elements in corridors.
-start will be different from finish.
-agentStart and agentTarget will each contain between 1 and 10 elements, inclusive.
-agentStart and agentTarget will contain the same number of elements.
-Each agent's starting room will be different from his target room.
-No agent will start in the same room as you.
-Each element of agentStart and agentTarget will be between 0 and N-1, inclusive, where N is the number of elements in corridors.
-There will be at least one path between each pair of rooms in the facility.
 

Examples

0)
    
{
"0100",
"1011",
"0100",
"0100"
}
{3}
{1}
0
2
Returns: 1.0
    3
    |
    |
0---1---2
The agent will always arrive at room 1 at the same time as you do, so there is no way to avoid capture.
1)
    
{
"01000",
"10110",
"01000",
"01001",
"00010"
}
{4}
{1}
0
2
Returns: 0.0
    2
    |
    |
0---1---3---4
You will reach room 1 before the agent does, so you will avoid capture.
2)
    
{
"010000",
"101011",
"010111",
"001000",
"011000",
"011000"
}
{4}
{5}
0
3
Returns: 0.5
     4
    / \
0--1---2--3
    \ /
     5
Your path must be 0-1-2-3. The agent is equally likely to take the paths 4-1-5 or 4-2-5. If he takes the first path, you will be captured in room 1. However, if he takes the second path, you will escape.
3)
    
{
"010000",
"101001",
"010110",
"001000",
"001000",
"010000"
}
{4}
{5}
0
3
Returns: 1.0
    5   4
    |   |
    |   |
0---1---2---3
You will be travelling through the corridor between rooms 1 and 2 at the same time the agent travels through the same corridor in the opposite direction.
4)
    
{
"01100",
"10011",
"10010",
"01100",
"01000"
}
{4,3}
{1,0}
0
3
Returns: 0.5
      0
     / \
4---1   2
     \ /
      3
Here you can choose between two paths. If you take path 0-1-3, you will always be captured by the first agent at room 1. However, if you take path 0-2-3, there is a 50% chance that you will be captured in room 2, depending on which path the second agent takes.
5)
    
{
"0100",
"1010",
"0101",
"0010"
}
{3}
{2}
0
3
Returns: 1.0
0--1--2--3
The agent reaches room 2 before you, but stays there indefinitely. You will then be captured as soon as you enter room 2.
6)
    
{"0101", "1010", "0101", "1010"}
{1}
{0}
0
1
Returns: 1.0
0 -- 1
|    | 
|    |
3----2
The longer path (0 -> 3 -> 2 -> 1) is absolutely safe, but you must take the shortest one (0 --> 1).
7)
    
{"011", "101", "110"}
{0}
{1}
2
1
Returns: 1.0
You are caught at the moment you enter room 1.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SortingWithPermutation

Sorting



Used in:

TCO09 Qual 1

Used as:

Division I Level One

Writer:

FedorTsarev

Testers:

PabloGilberto , legakis , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7952

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13742&pm=7952

Problem Statement

    A permutation p[0], p[1], ..., p[n-1] is a sequence containing each number from 0 to n-1 exactly once. The result of applying permutation p to an array a of length n is an array b of length n, where b[p[i]] = a[i] (0-based indices).

Given an array a, find a permutation which has the effect of sorting the elements of a in non-descending order, i.e., an order where each element is greater than or equal to the previous one. If there are several suitable permutations return the lexicographically smallest one.

The permutation p[0], p[1], ..., p[n-1] is considered lexicographically smaller than the permutation q[0], q[1], ..., q[n-1] if there is an index i such that p[i] < q[i] and the equation p[j] = q[j] holds for all j < i.
 

Definition

    
Class:SortingWithPermutation
Method:getPermutation
Parameters:int[]
Returns:int[]
Method signature:int[] getPermutation(int[] a)
(be sure your method is public)
    
 

Constraints

-a will contain between 1 and 50 elements, inclusive.
-Each element of a will be between 1 and 1000, inclusive.
 

Examples

0)
    
{2, 3, 1}
Returns: {1, 2, 0 }
The element that is originally at position 0 goes to position 1. The elements originally at positions 1 and 2 go to positions 2 and 0, respectively.
1)
    
{2, 1, 3, 1}
Returns: {2, 0, 3, 1 }
There are two suitable permutations - {2, 0, 3, 1} and {2, 1, 3, 0}. The first one is lexicographically smaller.
2)
    
{4, 1, 6, 1, 3, 6, 1, 4}
Returns: {4, 0, 6, 1, 3, 7, 2, 5 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RoadReconstruction

Graph Theory, Sorting, String Parsing



Used in:

SRM 356

Used as:

Division II Level Three

Writer:

Pawa

Testers:

PabloGilberto , brett1479 , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7921

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10765&pm=7921

Problem Statement

    There are several cities in the country, and some of them are connected by bidirectional roads. Unfortunately, some of the roads are damaged and cannot be used right now. Your goal is to rebuild enough of the damaged roads that there is a functional path between every pair of cities.

You are given String[] roads, each element of which describes a single road. Damaged roads are formatted as "id city1 city2 cost" and non-damaged roads are formatted as "id city1 city2" (all quotes for clarity). In this notation, id is the unique identifier of the road, and city1 and city2 are the case-sensitive names of the two cities directly connected by that road. If the road is damaged, cost represents the price of rebuilding that road. Each id will be formatted "Cx" (quotes for clarity), where C is an uppercase letter and x is a digit. Every city in the country will appear at least once in roads.

Return a String containing a single space separated list of the identifiers of the roads that must be rebuilt to achieve your goal. If there are multiple possibilities, select the one with the minimal total reconstruction cost. If a tie still exists, return the String that comes first lexicographically. If it is impossible to achieve your goal, return "IMPOSSIBLE" (quotes for clarity only).
 

Definition

    
Class:RoadReconstruction
Method:selectReconstruction
Parameters:String[]
Returns:String
Method signature:String selectReconstruction(String[] roads)
(be sure your method is public)
    
 

Notes

-There can be more than one road between a pair of cities.
 

Constraints

-roads will contain between 1 and 50 elements, inclusive.
-Each element of roads will contain between 6 and 50 characters, inclusive.
-Each element of roads will be formatted as "id city1 city2" or "id city1 city2 cost" (all quotes for clarity).
-Each id will be formatted as "Cx" (quotes for clarity), where C is an uppercase letter ('A'-'Z') and x is a digit ('0'-'9').
-Each id in roads will be distinct.
-Each city1 and city2 will contain between 1 and 45 letters ('a'-'z', 'A'-'Z'), inclusive.
-In each element of roads, city1 and city2 will be distinct.
-Each cost will be an integer between 1 and 1000, inclusive, with no leading zeroes.
 

Examples

0)
    
{"M1 Moscow Kiev 1", "M2 Minsk Kiev", "M3 Minsk Warsaw"}
Returns: "M1"
Rebuilding road M1 will make all three cities connected to each other.
1)
    
{"R1 NY Washington", "M1 Moscow StPetersburg 1000"}
Returns: "IMPOSSIBLE"
Even after reconstuction of the road M1, the resulting road network won't be connected. So, the answer is "IMPOSSIBLE".
2)
    
{"B1 Bratislava Havka"}
Returns: ""
3)
    
{"M1 Moscow StPetersburg 1", "M2 Moscow Saratov 2", "S0 Saratov StPetersburg"}}
Returns: "M1"
4)
    
{"O1 Beetown Fearnot 6","N7 Fearnot Hornytown","M8 Hornytown Belcher 10",
 "L5 Belcher Fearnot 8","C7 Fearnot Beetown 4","K7 Quiggleville Beetown 12",
 "H4 Beetown DryFork 6","Z0 Hornytown Belcher 1","O5 Belcher Quiggleville 10",
 "U7 Quiggleville Fearnot 2","A8 Fearnot Quiggleville 8","T6 Beetown DryFork 17",
 "E8 Quiggleville DryFork 8","Y4 DryFork Quiggleville 4","Q8 Hornytown DryFork 2",
 "J9 Quiggleville DryFork 19","M4 DryFork Quiggleville 7","T1 DryFork Fearnot 9",
 "G4 Fearnot DryFork 6","V9 Hornytown Beetown 5","O6 Quiggleville Beetown 4",
 "L8 Beetown Roachtown 5","D5 Belcher DryFork 8","W5 Belcher DryFork 1"}
Returns: "C7 L8 U7 W5 Z0"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

NowhereLand

Graph Theory



Used in:

SRM 442

Used as:

Division I Level Three

Writer:

mateuszek

Testers:

PabloGilberto , kalinov , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7891

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13750&pm=7891

Problem Statement

    

You are the king of Nowhere Land. You've recently received some big donations, so you've decided to hire more guards to protect your country. There are k different guarding companies in Nowhere Land. Each guarding company has agencies in various cities. If a guarding company has an agency in a city, then that company is allowed to have at most one guard working in that city. Otherwise, the company is not allowed to have any guards in that city. As long as you obey this rule, you can add as many new guards as you want. However, you cannot fire or move existing guards.

There's one problem though. Some pairs of cities cooperate with each other and have certain requirements when hiring guards. If city A cooperates with city B, and a certain company has a guard working in city A but not city B, that is considered a conflict. For each pair of cooperating cities, each distinct company that breaks this rule counts as a conflict, so there may be multiple conflicts within a single pair of cities.

You are given a String[] cities. The number of elements in cities is equal to the number of cities in Nowhere Land. The j-th character of the i-th element of cities is '1' (one) if cities i and j cooperate, and '0' (zero) otherwise. You are also given String[]s guards and agencies. The i-th element of guards is a space separated list of guarding companies that already have guards working in city i. The i-th element of agencies is a space separated list of guarding companies that have an agency in city i. Each guarding company is represented as an integer between 0 and k-1, inclusive. Return the minimum possible number of conflicts that can exist after hiring additional guards.

 

Definition

    
Class:NowhereLand
Method:placeGuards
Parameters:String[], int, String[], String[]
Returns:int
Method signature:int placeGuards(String[] cities, int k, String[] guards, String[] agencies)
(be sure your method is public)
    
 

Constraints

-cities will contain between 1 and 50 elements, inclusive.
-The number of characters in each element of cities will be equal to the number of elements in cities.
-Each character of each element of cities will be a zero ('0') or a one ('1').
-The i-th character of i-th element of cities will be '0'.
-The i-th character of j-th element of cities will be the same as the j-th character of i-th element.
-k will be between 1 and 50, inclusive.
-cities, guards and agencies will all contain the same number of elements.
-Each element of guards will contain between 0 and 50 characters, inclusive.
-Each element of guards will be a single space separated list of distinct integers between 0 and k - 1, inclusive, with no extra leading zeroes, without leading or trailing spaces.
-Each element of agencies will contain between 0 and 50 characters, inclusive.
-Each element of agencies will be a single space separated list of distinct integers between 0 and k - 1, inclusive, with no extra leading zeroes, without leading or trailing spaces.
-For each integer in the i-th element of guards, this integer will also be in the i-th element of agencies.
 

Examples

0)
    
{ "0111",
  "1000",
  "1000",
  "1000" }
1
{ "0", "", "", "" }
{ "0", "0", "", "0" }
Returns: 1
There's only one guarding company in Nowhere Land. You can hire additional guards in cities 1 and 3. The best solution is to hire guards in both these cities. Then there will be just one conflict (between cities 0 and 2).
1)
    
{ "011",
  "101",
  "110"  }
1
{ "0", "", "" }
{ "0", "", "" }
Returns: 2
You can't hire additional guards here. There are 2 conflicts (between cities 0 and 1 and cities 0 and 2).
2)
    
{ "011",
  "101",
  "110"  }
1
{ "", "", "" }	
{ "0", "0", "0" }
Returns: 0
There are two possible solutions. You can hire a guard in each of the three cities and get rid of all conflicts. Alternatively, don't hire anybody and there will also be no conflicts.
3)
    
{ "010100",
  "101100",
  "010011",
  "110010",
  "001100",
  "001000" }
3
{ "1 2", "", "1", "", "0", "0" }
{ "0 1 2", "0 1", "0 1 2", "1 2", "0", "0" }
Returns: 7
In this example there are 3 guarding companies. A possible solution is to hire a guard from company 0 in city 2 and guards from company 1 in cities 1 and 3. As a result, there will be 7 conflicts: two between cities 3 and 4 and one between cities 0 and 1, 0 and 3, 1 and 2, 2 and 4, 2 and 5.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CostMatrix

Graph Theory, Greedy



Used in:

TCO07 Semi 1

Used as:

Division I Level One

Writer:

Yarin

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7881

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10839&pm=7881

Problem Statement

    

An airline company has flights to all major cities in some country. From any major city it is possible to reach any other major city either by a direct flight, or by two or more flights. The company has provided a matrix containing the cheapest cost when taking a trip between any pair of major cities. When several flights are needed for a trip, the cost for that trip is the sum of the costs of the direct flights. The cost for a direct flight is a positive integer.

Given this matrix, you want to find the least possible total cost of all direct flights. You can assume that if a flight exists from A to B, another flight with the same cost exists from B to A (and you should only count one of these direct flights), and that no other flights between the same pair of cities exist with a different cost.

Create a class CostMatrix containing the method leastTotalCost which takes as input a String[] matrix, describing the cost matrix as a symmetric table. Each row i (0-indexed) will contain a single space separated list of integers, where the jth integer (0-indexed) in row i is the cheapest cost to take a trip between cities i and j. The diagonal entries will all be 0. The method should return an int, the least possible total cost for all direct flights. If the cost matrix is inconsistent, return -1.

 

Definition

    
Class:CostMatrix
Method:leastTotalCost
Parameters:String[]
Returns:int
Method signature:int leastTotalCost(String[] matrix)
(be sure your method is public)
    
 

Constraints

-matrix will contain between 2 and 20 elements, inclusive.
-Each element in matrix will be a single-space separated list of non-negative integers without leading or trailing spaces.
-The number of integers in each element in matrix will be the same as the number of elements in matrix.
-The ith integer in element j, where i != j, will be between 1 and 2500, inclusive, without leading zeros.
-The ith integer in element i will be 0.
-The ith integer in element j will be equal to the jth integer in element i.
 

Examples

0)
    
{"0 2 2",
 "2 0 2",
 "2 2 0"}
Returns: 6
The only possible network of flight routes consists of three direct flights, each with cost 2, connecting every pair of cities, for a total cost of 6.
1)
    
{"0 6 15 2 6",
 "6 0 9 8 12",
 "15 9 0 16 18",
 "2 8 16 0 4",
 "6 12 18 4 0"}
Returns: 55

The least possible cost consists of the direct flights:

City 0 - city 1 (cost 6)
City 1 - city 2 (cost 9)
City 0 - city 3 (cost 2)
City 2 - city 3 (cost 16)
City 3 - city 4 (cost 4)
City 2 - city 4 (cost 18)
2)
    
{"0 1 6 17 26 13 7 16",
 "1 0 5 16 25 12 7 15",
 "6 5 0 21 21 8 12 11",
 "17 16 21 0 41 28 23 31",
 "26 25 21 41 0 13 32 10",
 "13 12 8 28 13 0 19 3",
 "7 7 12 23 32 19 0 22",
 "16 15 11 31 10 3 22 0"}
Returns: 69
3)
    
{"0 1 3", 
 "1 0 1", 
 "3 1 0"}
Returns: -1
The cost matrix is inconsistent since it says the cheapest cost to travel between city 0 and 2 is 3, even though it obviously can be done at cost 2 by making an intermediate landing at city 1.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ConvexArray

Geometry, Search



Used in:

SRM 360

Used as:

Division I Level Three

Writer:

darnley

Testers:

PabloGilberto , Olexiy , lovro , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7877

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10772&pm=7877

Problem Statement

    

An array of integers is called convex if all of the following apply:

  • It contains an even number of elements.
  • It contains between 6 and 50 elements, inclusive.
  • Each element is an integer between 1 and 50, inclusive. Interpret the integers as the coordinates of n points: x_1, y_1, x_2, y_2, ..., x_n, y_n (in this order).
  • These n points are vertices of a convex polygon.
  • The vertices are listed in either clockwise or counterclockwise order.
  • No three consecutive vertices lie on the same straight line (when saying three consecutive vertices we also mean vertices number N, 1 and 2 and vertices number N-1, N and 1).

Given a int[] beginning, find the shortest int[] that will produce a valid convex array when appended to the end of beginning. If there are multiple such int[]s, return the one among them that comes first lexicographically. If there is no such int[], return a int[] containing a single element -1.

 

Definition

    
Class:ConvexArray
Method:getEnding
Parameters:int[]
Returns:int[]
Method signature:int[] getEnding(int[] beginning)
(be sure your method is public)
    
 

Constraints

-beginning will contain between 0 and 50 elements, inclusive.
-Each element of beginning will be between 1 and 50, inclusive.
 

Examples

0)
    
{1, 1, 2, 2}
Returns: {1, 2 }
The polygon must contain at least 3 points, so we need to add at least one more. Adding (1, 1) would give us a segment, not a polygon, thus we stick to the next lexicographical point which is (1, 2).
1)
    
{5, 6, 6}
Returns: {1, 1, 1 }
It is possible that the x coordinate is given and you have to choose the y coordinate.
2)
    
{1, 3}
Returns: {1, 1, 2, 1 }
(1, 1, 1, X) would form a segment, not a triangle. Move on to the next lexicographical quadruple, (1, 1, 2, 1).
3)
    
{2, 5, 5, 5, 4, 4, 3}
Returns: {4 }


We need to find the y coordinate for the last vertex that will generate a convex polygon. Points (3, 1) and (3, 2) would make the polygon non-convex. Point (3, 3) would break the rules because there would be three consecutive vertices on the same straight line. Point (3, 4) is the only valid choice.
4)
    
{1, 1, 2, 3, 3, 1, 1, 2, 3}
Returns: {-1 }


No matter what the last y-coordinate is, the edge (1, 1)-(2, 3) intersects the edge (3, 1)-(1, 2), so there is no convex polygon possible.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PrinceOfPersia

Graph Theory, Search



Used in:

SRM 360

Used as:

Division I Level Two

Writer:

darnley

Testers:

PabloGilberto , Olexiy , lovro , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7876

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10772&pm=7876

Problem Statement

    

A maze is a rectangular grid, where each cell is either an empty space or an obstacle. The Prince of Persia is initially positioned in one empty cell, and the Princess is in another one.

Each of them can move from one empty cell to another one only if these cells are adjacent, i. e., share a common side. None of them can appear in a cell with an obstacle.

Their common target is to move into the same cell.

The terrible usurper Jaffar doesn't want that to happen. He is going to put obstacles into some currently empty cells in order to prevent their meeting. He cannot put the obstacles in the cells where the Prince and the Princess are initially located, but he can use any other empty cells.

You will be given a String[] maze containing empty cells ('.'), obstacles ('#') and the initial positions of the Prince and the Princess ('P').

Return the minimum number of obstacles that Jaffar must put to separate the Prince and the Princess. If he is unable to separate them, return -1.

 

Definition

    
Class:PrinceOfPersia
Method:minObstacles
Parameters:String[]
Returns:int
Method signature:int minObstacles(String[] maze)
(be sure your method is public)
    
 

Constraints

-maze will contain between 1 and 10 elements, inclusive.
-Each element of maze will contain between 1 and 10 characters, inclusive.
-Each element of maze will contain the same number of characters.
-Each element of maze will contain only dots ('.'), number signs ('#') and uppercase 'P' characters.
-There will be exactly two 'P' characters in the elements of maze.
 

Examples

0)
    
{"P....",
 "...##",
 "##...",
 "....P"}
Returns: 1
Jaffar will put an obstacle in one of the two central cells of the maze.
1)
    
{".....",
 ".P.P.",
 "....."}
Returns: 3
One of the solutions for Jaffar that uses 3 obstacles is to build a "wall" in the middle column.
2)
    
{".#P.",
 ".P#."}
Returns: 0
The royal persons are already securely separated.
3)
    
{"####",
 "#PP#",
 "####"}
Returns: -1
Remember, Jaffar can't put an obstacle in a cell marked "P".

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RelabelingOfGraph

Graph Theory



Used in:

SRM 365

Used as:

Division I Level Three

Writer:

Xixas

Testers:

PabloGilberto , Yarin , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7860

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10780&pm=7860

Problem Statement

    Given a directed graph on n vertices, your task is to label its vertices as follows:
  1. Each vertex must be labeled with a distinct number between 0 and n-1, inclusive.
  2. For every edge in the graph from vertex v1 to vertex v2, v2's label must be greater than v1's label.
You are given a String[] m containing the adjacency matrix of the original graph. The j-th character of the i-th element of m is '1' (one) if there is an edge in the graph from the i-th vertex to the j-th vertex, or '0' (zero) otherwise.

Return the labeling as a int[], where the i-th element of the int[] is the label of the i-th vertex.  If there is more than one possible labeling, return the one that comes first lexicographically.  If there is no valid way to label the vertices, return an empty int[].
 

Definition

    
Class:RelabelingOfGraph
Method:renumberVertices
Parameters:String[]
Returns:int[]
Method signature:int[] renumberVertices(String[] m)
(be sure your method is public)
    
 

Notes

-int[] a comes before int[] b lexicographically if a[i] < b[i] , where i is the first position in which a and b differ.
 

Constraints

-m will contain between 1 and 50 elements, inclusive.
-Each element of m will contain exactly n characters, where n is the number of elements in m.
-Each character in each element of m will be '1' (one) or '0' (zero).
-The i-th character of the i-th element of m will be '0'.
 

Examples

0)
    
{"0100", "0010", "0001", "0000"}
Returns: {0, 1, 2, 3 }
A chain consisting of 4 vertices.
1)
    
{"010", "001", "100"}
Returns: { }
We have a cycle of 3 vertices and hence can not enumerate the vertices in the desired fashion.
2)
    
{"00001", "00010", "00000", "00001", "00100"}
Returns: {0, 1, 4, 2, 3 }
3)
    
{"0"}
Returns: {0 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RepeatingFreeStrings

Advanced Math



Used in:

TCO07 Finals

Used as:

Division I Level Three

Writer:

Mike Mirzayanov

Testers:

PabloGilberto , Yarin , legakis , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7849

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10843&pm=7849

Problem Statement

    

A binary string s is called "repeating free" if no proper prefix equals a proper suffix of the same lengh. A substring is called "proper" if it differs from the whole string. For example, strings "0101011", "10", "10111100" are repeating free, but the string "01101011" is not.

Return the k-th string among all repeating free strings with length n in lexicographical order (k is a 0-based index). Return an empty string if it doesn't exist.

 

Definition

    
Class:RepeatingFreeStrings
Method:kthString
Parameters:int, int
Returns:String
Method signature:String kthString(int n, int k)
(be sure your method is public)
    
 

Constraints

-n will be between 1 and 50, inclusive.
-k will be between 0 and 2000000000, inclusive.
 

Examples

0)
    
2
0
Returns: "01"
All repeating free strings of length 2 are "01" and "10".
1)
    
2
1
Returns: "10"
2)
    
3
2
Returns: "100"
All repeating strings of length 3 are "001", "011", "100", "110".
3)
    
5
2
Returns: "00101"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SharksDinner

Graph Theory



Used in:

SRM 358

Used as:

Division I Level Three

Writer:

icanadi

Testers:

PabloGilberto , brett1479 , Olexiy , Andrew_Lazarev

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7834

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10768&pm=7834

Problem Statement

    Some sharks are having dinner and they are eating each other. For every shark we know its size, speed and intelligence (measured in positive integers). Shark A can eat shark B if and only if A's size, speed and intelligence are all greater than or equal to B's. Due to digestive restrictions, each shark can eat at most two other sharks.



Given int[] size, int[] speed and int[] intelligence, return the minimum number of sharks that will survive.
 

Definition

    
Class:SharksDinner
Method:minSurvivors
Parameters:int[], int[], int[]
Returns:int
Method signature:int minSurvivors(int[] size, int[] speed, int[] intelligence)
(be sure your method is public)
    
 

Constraints

-size, speed and intelligence will contain the same number of elements.
-size, speed and intelligence will each contain between 1 and 50 elements, inclusive.
-Each element of size, speed and intelligence will be between 1 and 2,000,000,000, inclusive.
 

Examples

0)
    
{ 1, 4, 3 }
{ 2, 3, 1 }
{ 1, 5, 2 }
Returns: 1
Shark 1 eats sharks 0 and 2 so we get 1 survivor.
1)
    
{ 4, 10, 5, 8, 8 }
{ 5, 10, 7, 7, 10 }
{ 5, 8, 10, 7, 3 }
Returns: 2
Shark 2 eats shark 0, and shark 1 eats sharks 3 and 4.
2)
    
{ 1, 2, 3, 4, 100 }
{ 4, 3, 2, 1, 100 }
{ 2, 4, 1, 3, 100 }
Returns: 3
The big shark eats two of the smaller sharks and is not hungry anymore, so the other two of the smaller sharks are lucky (and they cannot eat each other).
3)
    
{ 4, 4, 4, 4 }
{ 3, 3, 3, 3 }
{ 8, 8, 8, 8 }
Returns: 1
Sharks with the same level of speed, size and intelligence can eat each other.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WallClimbing

Geometry, Graph Theory



Used in:

Member Beta

Used as:

Division I Level Three

Writer:

Nickolas

Testers:

Rustyoldman , timmac , StevieT , vexorian

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7832

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13935&pm=7832

Problem Statement

    A robot needs to climb a flat vertical wall with several handholds on it.



The robot has four mechanial "hands". Each hand can grab a handhold positioned anywhere within or on the boundary of a circle of radius armLength from robot's center. While the robot is climbing the wall, three of the hands have to remain anchored at three distinct handholds at all times. To move between holding positions, the robot can use the fourth hand to grab next handhold and release one of the previous handholds. At the start of the climb the robot can stand on one of its hands anywhere on the ground. Thus, it can grab any single handhold which is not higher than 2*armLength from the ground, and to start climbing it must grab three handholds while still standing on the fourth hand.



The wall is described as a plane with a cartesian coordinate system on it. The ground is the line y = 0. Handhold i is positioned at the point (holdx[i], holdy[i]).



Return the y-coordinate of the highest point the robot can reach with a hand while standing on the ground or hanging on the wall using the other three hands.
 

Definition

    
Class:WallClimbing
Method:maxHeight
Parameters:int[], int[], int
Returns:double
Method signature:double maxHeight(int[] holdx, int[] holdy, int armLength)
(be sure your method is public)
    
 

Notes

-The robot can't grab one handhold with two or more hands.
-The returned value must have an absolute or relative error less than 1e-9.
 

Constraints

-holdx will contain between 1 and 16 elements, inclusive.
-holdy will contain the same number of elements as holdx.
-Each element of holdx and holdy will be between 1 and 1000, inclusive.
-The location of each handhold will be distinct.
-handLength will be between 1 and 100, inclusive.
 

Examples

0)
    
{10, 10, 10}
{20, 40, 60}
30
Returns: 80.0
The three handholds are arranged in a vertical line, and it is possible to hang on them and reach 80.0.
1)
    
{20, 40, 60, 80}
{20, 20, 20, 20}
20
Returns: 40.0
The four handholds are arranged in a horizontal line. It is possible to hang on any three successive handholds, but this doesn't let the robot reach higher than from the ground.
2)
    
{10, 10, 10, 10,  10,  10,  10,  10,  10}
{20, 40, 60, 80, 100, 120, 140, 160, 180}
30
Returns: 200.0
Each triple of successive handholds is a valid holding position, and it is possible to get to the triple {6,7,8} and reach a height of 200.
3)
    
{10, 10}
{10, 20}
40
Returns: 80.0
There are not enough handholds to hang on them.
4)
    
{ 50, 100, 150, 200,
  50, 100, 150, 200,
  50, 100, 150, 200,
  50, 100, 150, 200}
{ 50,  50,  50,  50,
 100, 100, 100, 100,
 150, 150, 150, 150,
 200, 200, 200, 200}
25
Returns: 50.0
Here no three handholds are close enough together for the robot to hang from them.
5)
    
{ 50, 100, 150, 200,
  50, 100, 150, 200,
  50, 100, 150, 200,
  50, 100, 150, 200}
{ 50,  50,  50,  50,
 100, 100, 100, 100,
 150, 150, 150, 150,
 200, 200, 200, 200}
50
Returns: 250.0
The robot can move to the highest row and hang on a horizontal triple.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ExploringHoneycombs

Graph Theory



Used in:

TCHS SRM 34

Used as:

Division I Level Three

Writer:

Nickolas

Testers:

PabloGilberto , brett1479 , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7831

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10769&pm=7831

Problem Statement

    A bee is exploring honeycombs with hexagonal cells. Each cell can have a maximum of 6 adjacent cells: two in the same column, two in a column to the left, and two in a column to the right. Cells with less than 6 adjacent cells are considered boundary cells.



Some cells are empty, some contain one portion of honey, and some are filled with wax. The bee cannot pass through wax-filled cells. When the bee passes through a honey-filled cell, it can collect the one portion of honey from that cell if it wants to. After a cell is harvested, it becomes empty. The bee initially flies to an empty or honey-filled boundary cell. It then walks from cell to adjacent cell collecting honey until it reaches an empty or honey-filled boundary cell. Finally, it flies away. The bee cannot fly between cells while it's collecting honey. Each walk from a cell to an adjacent cell counts as one move. The arrival and departure flights do not count as moves.



You are given a String[] cells representing a fragment of honeycombs. '.' characters represent free space (no cell), 'E' characters are empty cells, 'H' characters are honey-filled cells, 'W' characters are wax-filled cells. Columns of honeycomb cells correspond to columns of characters in cells. Element 0 of cells corresponds to the highest row of honeycombs. If we assign 0-based indices to columns, odd columns (1,3,...) will begin half-a-cell lower than the even columns (0,2,...) (see examples for further clarification).



Return the minimal number of moves required for the bee to arrive, collect exactly n portions of honey, and depart.
 

Definition

    
Class:ExploringHoneycombs
Method:minWay
Parameters:String[], int
Returns:int
Method signature:int minWay(String[] cells, int n)
(be sure your method is public)
    
 

Notes

-There are no cells outside the fragment of honeycombs represented with cells, so all border cells are boundary.
-Cells that are adjacent to free space ('.') are boundary cells.
 

Constraints

-n will be between 1 and 9, inclusive.
-The number of 'H' characters in cells will be between n and 9, inclusive.
-cells will contain between 1 and 50 elements, inclusive.
-Each element of cells will contain between 1 and 50 characters, inclusive.
-All elements of cells will contain the same number of characters.
-Each character in cells will be '.', 'E', 'W' or 'H'.
-The empty and honey-filled cells of the honeycombs will be connected, i.e., the bee will be able to walk from any such cell to any another cell.
-There will be at least one boundary cell not filled with wax.
 

Examples

0)
    
{".E.",
 "EHW",
 "EEE"}
1
Returns: 2

Honeycombs look like this. The bee needs one step to move from any empty border cell to the honey cell in the middle and one step to return.

1)
    
{"HWWWW",
 "EHEHW",
 "WWWWW"}
1
Returns: 0
The bee can fly to the upper-left cell, collect the honey from it and depart without moving.
2)
    
{"WWWWW",
 "HHHHH",
 "WWWWW"}
4
Returns: 4
The bee has to start at any end of the "tunnel", and when it collects 4 portions of honey, it will be better to pass the last cell with honey (not collecting it) than to return through the empty cells.
3)
    
{".EEE.",
 "EHHHE",
 "EH.HE",
 "EEHEE",
 "..E.."}
6
Returns: 5
4)
    
{"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEHW",
 "WEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWEW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWEW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWEW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWEW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWEW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWEW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWEW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWEW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWEW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWEW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWEW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEW",
 "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWEW"}
1
Returns: 2302
5)
    
{"....",
 ".H.H",
 "H.H."}
4
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LateForConcert

Graph Theory



Used in:

SRM 366

Used as:

Division I Level Three

Writer:

jthread

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7827

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10781&pm=7827

Problem Statement

    

You are a guitar player and you are giving a concert tonight. Unfortunately, you are running a bit late, and you still need to travel across town to get to the concert hall. You will drive as fast as possible (above the speed limit) and you are willing to drive through red lights at the risk of getting fined. However, you do not want to arrive early because you don't like the artist playing before you. Your goal is to get to the concert hall exactly on time.



The city is a rectangular grid of squares described by the String[] cityMap. The j-th character of the i-th element of cityMap is the square at row i, column j. Each square is one of the following:

  • X: A house. You cannot enter this square.
  • .: A safe road. You can drive here safely without ever getting a speeding ticket.
  • Y: Your starting location. After time = 0, this becomes a safe road.
  • C: The concert hall. As soon as you enter this square, you are at your final destination and you cannot leave.
  • T: A traffic light. See below for details.
  • S: A speed trap. You will get fined speedingTicket dollars every time you enter a square containing a speed trap.

You are given an int timeLeft, the number of seconds you have left until your concert starts. At time 0, you are at your starting location. At the speed you are driving, it takes you exactly one second to move to any of the 4 adjacent squares. At each second, you must move to an adjacent square unless you are at a traffic light. You are never allowed to directly go back to the immediately previous square of your path. If you are currently at a traffic light, you have two options: make a move during the upcoming second (like you would from any other square), or stay at the traffic light for exactly one second before making your next move. If you stay at the traffic light for one second, you are guaranteed to not get fined. Otherwise, you have a 70% chance of getting fined redLight dollars.



Determine the route that will take you to the concert hall in exactly timeLeft seconds. If there are multiple such routes, choose the one that minimizes your total expected fine. Return your total expected fine, or -1 if there is no way to get to the concert hall exactly on time.

 

Definition

    
Class:LateForConcert
Method:bestRoute
Parameters:String[], int, double, double
Returns:double
Method signature:double bestRoute(String[] cityMap, int timeLeft, double speedingTicket, double redLight)
(be sure your method is public)
    
 

Notes

-The returned value must be accurate to within a relative or absolute value of 1E-9.
 

Constraints

-cityMap will contain between 1 and 50 elements, inclusive.
-Each element of cityMap will contain between 1 and 50 characters, inclusive.
-Each element of cityMap will contain the same number of characters.
-Each character of cityMap will be one of the following: 'X', '.', 'Y', 'C', 'T' or 'S'.
-Exactly one character in cityMap will be 'Y'.
-Exactly one character in cityMap will be 'C'.
-timeLeft will be between 1 and 100, inclusive.
-speedingTicket will be between 1.0 and 1000.0, inclusive.
-redLight will be between 1.0 and 1000.0, inclusive.
 

Examples

0)
    
{"XXXXXXXX",
 "XY...S.X",
 "XXXXXX.X",
 "C..S.TT."}
14
60
93
Returns: 185.1
If you wait for one of the traffic lights, it will take 14 seconds, and your expected total fine will be speedingTicket + speedingTicket + 0.7 * redLight.
1)
    
{"XX..XX",
 "Y....C"}
9
52
874
Returns: 0.0
You can use the 2x2 square to spend your time so you don't have to see the other artist.
2)
    
{"YTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTC"}
67
123.4
42.192
Returns: 886.032
3)
    
{"C.......",
 "SXXSXXX.",
 "TSSTY..."}
12
1.23456789
123.456789
Returns: 0.0
The shortest route is not always the best!
4)
    
{"Y..",
 "...",
 "..C"}
3
1.0
1.0
Returns: -1.0
The concert hall is too far, so you don't have enough time to reach it.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WSNParentsAssignment

Graph Theory



Used in:

SRM 367

Used as:

Division I Level Three

Writer:

gevak

Testers:

PabloGilberto , Yarin , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7816

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10783&pm=7816

Problem Statement

    

A wireless sensor network consists of several independent measuring devices and one control center. Each device must be able to send its sensor readings to the control center, but due to limitations in range, not all of the devices can communicate directly with the control center. To solve this problem, each device is assigned a single parent to which it is capable of directly transmitting data. A parent can be either another device or the control center. Each device receives readings from all its children (if it has any), adds its own readings, and passes everything to its parent. All the readings must eventually reach the control center. The number of children a device has is called the device's burden level. The burden level of the entire network is the maximum burden level among all its devices. Note that the control center is not a device.

You are given a String[] network, where the j-th character of the i-th element is equal to 'Y' if the i-th device can directly transmit data to the j-th device, and 'N' otherwise. A wireless sensor network in this problem always represents a directed acyclic graph, so if device d1 can transmit data directly or indirectly to device d2, then device d2 can't transmit data directly or indirectly to device d1. You are also given a String nearest, the i-th character of which is 'Y' if the i-th device can communicate directly with the control center, and 'N' otherwise. You must assign a parent to each device in a way that minimizes the burden level of the entire network. Return a int[], the i-th element of which is the parent assigned to the i-th device. If the parent is another device, the i-th element must be the 0-based index of the parent device. If the parent is the control center, the i-th element must be n, where n is the number of devices in the network. If there are multiple possible return values, return the one among them that comes first lexicographically. If it is not possible to assign parents in such a way that the control center can receive all the devices' readings, return an empty int[].

 

Definition

    
Class:WSNParentsAssignment
Method:minNetworkBurdenLevel
Parameters:String[], String
Returns:int[]
Method signature:int[] minNetworkBurdenLevel(String[] network, String nearest)
(be sure your method is public)
    
 

Notes

-A int[] a1 comes before a int[] a2 lexicographically if a1 contains a smaller value at the first index at which they differ.
 

Constraints

-network will contain between 1 and 50 elements, inclusive.
-Each element of network will contain exactly n characters, where n is the number of elements in network.
-Each element of network will contain characters 'N' and 'Y' only.
-network will represent a directed acyclic graph.
-nearest will contain exactly n characters, where n is the number of elements in network.
-nearest will contain characters 'N' and 'Y' only.
 

Examples

0)
    
{"NNY","NNY","NNN"}
"NNY"
Returns: {2, 2, 3 }


There is only one possible configuration here. Assign device 2 as the parent of devices 0 and 1, and assign the control center as the parent of device 2. The network's burden level here is 2.
1)
    
{"NYY","NNY","NNN"}
"NNY"
Returns: {1, 2, 3 }


This is similar to example 0, but in this case, device 0 can transmit data directly to device 1. Therefore, we assign device 1 as the parent of device 0 because that reduces the network's burden level to 1.
2)
    
{"NYNNNN","NNNNNN","NYNYNN","NNNNNN","NYNYNN","NYNNNN"}
"NYNYNN"
Returns: {1, 6, 3, 6, 3, 1 }
3)
    
{"N"}
"Y"
Returns: {1 }
4)
    
{"N"}
"N"
Returns: { }
There is only one device here, and it cannot communicate directly with the control center. Therefore, it is impossible for the control center to get readings from the device.
5)
    
{"NNNNN","YNNNY","NNNYN","NNNNN","YNNYN"}
"YNNYN"
Returns: {5, 4, 3, 5, 0 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RoadsReorganization

Dynamic Programming



Used in:

TCHS07 Finals

Used as:

Division I Level Three

Writer:

Mike Mirzayanov

Testers:

PabloGilberto , brett1479 , Olexiy , marian

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7808

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10764&pm=7808

Problem Statement

    

A Kingdom consists of several cities, some of which are connected by bidirectional roads. For any two cities A and B, there is exactly one simple path between them (a path is simple if it doesn't contain any city more than once). In terms of graph theory, the roads network in the Kingdom is a tree.

Unfortunately, the new King does not like trees, so he wants the road network to be a loop. In other words, each city must be directly connected to exactly 2 other cities, and for any two cities there still must be at least one path between them.

You will be given a String[] kingdom, representing the roads in the Kingdom. The i-th character in the j-th element of kingdom is equal to '1' (one) if there is a road between the i-th and the j-th cities, and '0' (zero) otherwise. Given that destroying a road or building a new road takes exactly one day, and knowing that King has only enough workers to perform 1 task per day, return the minimal number of days King needs to change the network to satisfy the new requirements. See examples for further clarification.

 

Definition

    
Class:RoadsReorganization
Method:minDaysCount
Parameters:String[]
Returns:int
Method signature:int minDaysCount(String[] kingdom)
(be sure your method is public)
    
 

Constraints

-kingdom will contain between 3 and 50 elements, inclusive.
-Each element of kingdom will contain exactly n characters, where n is the number of elements in kingdom.
-Each element of kingdom will contain only '0' (zero) and '1' (one) characters.
-The j-th character in the i-th element of kingdom will be equal to the i-th character in the j-th element of kingdom.
-The i-th character in the i-th element of kingdom will be '0'.
-There will be exactly one simple path between every pair of cities.
 

Examples

0)
    
{"010", "101", "010"}
Returns: 1
One day is needed to add the road between the 0-th and 2-nd cities.
1)
    
{"0111",
 "1000",
 "1000",
 "1000"}
Returns: 3
Remove any single road, and add another two.
2)
    
{"01010", "10100", "01000", "10001", "00010"}
Returns: 1
Add one road between the 2-nd and 4-th cities.
3)
    
{"0100100", "1011000", "0100000", "0100000", "1000011", "0000100", "0000100"}
Returns: 5
4)
    
{"011111", "100000", "100000", "100000", "100000", "100000"}
Returns: 7

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Shapes

Brute Force, Recursion, String Parsing



Used in:

TCHS SRM 40

Used as:

Division I Level Three

Writer:

StevieT

Testers:

PabloGilberto , brett1479 , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7791

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10784&pm=7791

Problem Statement

    Your friend has set a challenge for you. He took a square piece of paper, on which was drawn a square grid parallel to the sides, and divided it up into 5 pieces by making cuts along the grid-lines. Your challenge is to reconstruct the original square from the pieces.



You are given an int L containing the length in grid units of the sides of the original square and 5 String[]s: s1, s2, s3, s4 and s5, each containing the details of the shape of one of the pieces of paper. Each character in each shape corresponds to a single square of the grid and will be a '#' if the square is present and a '.' if not. The shapes are given to you in the same orientation that they were in as part of the original square (i.e., they have not been rotated or turned over since they were cut out).



Return a String[] containing the reconstructed square. The return value should contain L Strings of length L. Character j of element i of the return value should be a digit containing the number of the shape (i.e., the digit in the supplied variable name) that the grid-square at position (i, j) was a part of. If there are multiple solutions, return the one that comes first lexicographically. The lexicographically earlier of two String[]s is the one with the lexicographically earlier String in the first position at which they differ. If there is no valid way of reconstructing the square, then your friend must be cheating and you should return a String[] containing a single element, "CHEAT" (quotes for clarity).



The shapes must not overlap in the reconstructed square or extend outside its boundary.
 

Definition

    
Class:Shapes
Method:reconstructSquare
Parameters:int, String[], String[], String[], String[], String[]
Returns:String[]
Method signature:String[] reconstructSquare(int L, String[] s1, String[] s2, String[] s3, String[] s4, String[] s5)
(be sure your method is public)
    
 

Constraints

-L will be between 3 and 10, inclusive.
-s1, s2, s3, s4 and s5 will each contain between 1 and L elements, inclusive.
-Each element of s1, s2, s3, s4 and s5 will contain between 1 and L characters, inclusive.
-Within each of s1, s2, s3, s4 and s5, every element will contain the same number of characters.
-Each character in s1, s2, s3, s4 and s5 will be either a '#' or a '.'.
-The first and last rows of s1, s2, s3, s4 and s5 will each contain at least 1 '#' character.
-The first and last columns of s1, s2, s3, s4 and s5 will each contain at least 1 '#' character.
-The '#' characters in each of s1, s2, s3, s4 and s5 will be connected.
 

Examples

0)
    
5
{"#####"}
{"#####"}
{"#####"}
{"#####"}
{"#####"}
Returns: {"11111", "22222", "33333", "44444", "55555" }
Here your friend cut the paper into strips. There are many ways that the square could be reconstructed, so we choose the lexicographically earliest.
1)
    
10
{"##"
,"##"}
{"########"
,"#......#"
,"#......#"
,"#......#"
,"#......#"
,"#......#"
,"#......#"
,"########"}
{"######"
,"#....#"
,"#....#"
,"#....#"
,"#....#"
,"######"}
{"####"
,"#..#"
,"#..#"
,"####"}
{"##########"
,"#........#"
,"#........#"
,"#........#"
,"#........#"
,"#........#"
,"#........#"
,"#........#"
,"#........#"
,"##########"}
Returns: 
{"5555555555",
"5222222225",
"5233333325",
"5234444325",
"5234114325",
"5234114325",
"5234444325",
"5233333325",
"5222222225",
"5555555555" }
This time your friend cut up the paper into rings.
2)
    
8
{"#....."
,"######"
,"######"}
{".###"
,"####"
,"####"}
{"###.."
,"###.."
,"##..."
,"####."
,"#####"
,".####"}
{".#"
,".#"
,".#"
,"##"
,"##"}
{"####."
,"#####"
,"..###"}
Returns: {"CHEAT" }
These shapes cannot form a square.
3)
    
5
{"#####"}
{"#####"}
{"#####","#####"}
{"#####"}
{"#####"}
Returns: {"CHEAT" }
4)
    
6
{"##",".#"}
{".#","##","##","##"}
{"##.","###","###","##."}
{"...#..","..##..","######","######"}
{"#"}
Returns: {"331152", "333122", "333422", "334422", "444444", "444444" }
5)
    
8
{"##.....",".#####.","....###"}
{"#....","####.","####.","####.","#####","..###","..###"}
{".###","..##","...#","####","####",".###",".###",".###"}
{"##","##"}
{"###"}
Returns: 
{"11555333",
"21111133",
"22221113",
"22223333",
"22223333",
"22222333",
"44222333",
"44222333" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PlaneDivision

Advanced Math, Geometry, Graph Theory



Used in:

SRM 350

Used as:

Division I Level Three

Writer:

Xixas

Testers:

PabloGilberto , brett1479 , Olexiy , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7788

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10674&pm=7788

Problem Statement

    You are given n distinct straight lines in the plane. The i-th line is specified by two distinct lattice points (x1[i], y1[i]) and (x2[i], y2[i]) that lie on it. These lines divide the plane into regions, and your task is to compute and return the number of finite regions among them. By a finite region we mean a convex polygon bounded by the given lines, with no points belonging to any of the given lines in its interior.
 

Definition

    
Class:PlaneDivision
Method:howManyFiniteParts
Parameters:int[], int[], int[], int[]
Returns:int
Method signature:int howManyFiniteParts(int[] x1, int[] y1, int[] x2, int[] y2)
(be sure your method is public)
    
 

Notes

-By a lattice point (x, y) we mean a point on the Cartesian plane with integer coordinates x and y.
-Two points are said to be distinct if either their x-coordinates or y-coordinates differ.
 

Constraints

-x1, y1, x2 and y2 will contain the same number of elements.
-x1, y1, x2 and y2 will contain between 1 and 50 elements, inclusive.
-All the elements of x1, y1, x2 and y2 will be between -10000 and 10000, inclusive.
-(x1[i], y1[i]) and (x2[i], y2[i]) will be distinct for all i (i.e., every two points defining a given line will be distinct).
-All the lines defined by (x1[i], y1[i]) and (x2[i], y2[i]) will be distinct.
 

Examples

0)
    
{0}
{0}
{1}
{1}
Returns: 0
A single line divides the plane into two infinite regions.
1)
    
{0, 1, 2}
{0, 1, -1}
{1, 2, 0}
{1, -1, 0}
Returns: 1
The three lines are the sidelines of a triangle which is the only finite region in this case.
2)
    
{-10000, -9999, 10000, -9999, 0, 500, -500}
{-9999, 10000, 9999, -10000, 0, 0, 0}
{-10000, 9999, 10000, 9999, 0, 500, -500}
{9999, 10000, -9999, -10000, 1, -1, -2}
Returns: 4
The only finite regions are the 4 big rectangles.
3)
    
{0, 0, 0, 0, 0, 0, 0, 0, 0}
{0, 0, 0, 0, 0, 0, 0, 0, 0}
{1, 1, 1, 1, 1, 1, 1, 1, 1}
{1, 2, 3, 4, 5, 6, 7, 8, 9}
Returns: 0
All the lines pass through the origin.
4)
    
{-1, -1, -1, -1, 1, 3, -3}
{-1, -2, 0, 0, 10000, 1, -5}
{1, 1, 1, -1, 1, -3, 3}
{1, 0, 2, -10000, 0, -2, 4}
Returns: 7
1 parallelogramm and 6 triangles are the only finite regions in this case.
5)
    
{-100, -100, -100, -100, -100}
{-100, -99, -98, -97, -96}
{100, 100, 100, 100, 100}
{99, 100, 101, 102, 103}
Returns: 0
5 parallel lines do not produce any finite regions.
6)
    
{-100, -100, -100, -100, -100, 1}
{-100, -99, -98, -97, -96, -1}
{100, 100, 100, 100, 100, -2}
{99, 100, 101, 102, 103, 2}
Returns: 0
A configuration of 5 parallel lines and a single line crossing all of them again yields no finite regions.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FreeGuitars

Graph Theory



Used in:

TC China 08 - 1D

Used as:

Division I Level Three

Writer:

jthread

Testers:

PabloGilberto , Olexiy , Andrew_Lazarev

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7783

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13676&pm=7783

Problem Statement

    

You are a guitar player and because you are really good, several music stores are giving you guitars for free! Unfortunately, you will have to travel to all the music stores to pick up your guitars. Because you don't have a drivers license and it's too far to go by bike, you decide to travel by train. But before you go, you first write a program to determine the minimum amount of money you have to spend to get to all the music stores by train.



You will be given an int N, the number of music stores there are (so also the numbers of guitars you get!), and a String[] trainRoutes, containing a list of train routes between the music stores. Each element of trainRoutes will be in the form of:

"STORE1 STORE2 TICKET" (quotes for clarity only)

STORE1 and STORE2 will be integers between 1 and N, inclusive, and TICKET will be the price for a round trip ticket from STORE1 to STORE2 and back. There will no more then 1 train route between each pair of stores, and there will not be a train route from a store to itself.



A round trip ticket is a ticket that allows you to travel the route in both directions exactly once. So buying a ticket between 3 and 5 means that you can travel from 3 to 5 one time, and from 5 to 3 one time. The 2 trips do not necessarily have to be in that order or directly after each other.



Return an int containing the minimum amount of money you will need to spend on train tickets to pick up all your free guitars. If it is not possible to pick up all N guitars, return -1. Initially, you are at store 1, and you want to return there after you picked up all guitars.

 

Definition

    
Class:FreeGuitars
Method:minimumCosts
Parameters:int, String[]
Returns:int
Method signature:int minimumCosts(int N, String[] trainRoutes)
(be sure your method is public)
    
 

Constraints

-N will be between 2 and 50, inclusive.
-trainRoutes will contain between 1 and 50 elements, inclusive.
-Each element of trainRoutes will be formatted "STORE1 STORE2 TICKET" (quotes for clarity).
-Each STORE1 and STORE2 will be integers between 1 and N, inclusive, with no leading zeroes.
-Each TICKET will be an integer between 0 and 100, inclusive, with no extra leading zeroes.
-All elements of trainRoutes will describe different routes (so there will no more then 1 train route between each pair of stores).
-No elements of trainRoutes will describe a route from a store to itself, so STORE1 never equals STORE2.
 

Examples

0)
    
3
{"1 2 6", "1 3 4", "2 3 1"}
Returns: 5
Here we take the train from 1 to 3, pick up the guitar at 3, then go from 3 to 2, pick up the guitar, and go back to 3 and 2 (you already paid for those trips) to 1 (where you can pick up the last guitar).
1)
    
3
{"1 3 56"}
Returns: -1
Whoops, we can not reach store 2!
2)
    
5
{"1 2 88",
"1 3 37",
"1 4 73",
"1 5 58",
"2 3 59",
"2 4 30",
"2 5 98",
"3 4 28",
"3 5 85",
"4 5 82"}
Returns: 153
3)
    
15
{"12 2 90", "14 4 11", "6 4 18", "5 8 35", "7 13 54", "11 2 33", "12 5 52",
 "13 2 98", "10 3 3", "4 7 63", "15 11 46", "11 7 4", "11 6 24", "9 7 30",
 "13 12 19", "5 10 82", "9 1 94", "13 3 30", "11 5 12", "10 1 10", "6 9 74",
 "12 8 55", "4 11 3", "12 4 71", "9 10 90"}
Returns: 306

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WorstCaseQuicksort

Dynamic Programming, Greedy



Used in:

TCO07 Semi 1

Used as:

Division I Level Three

Writer:

Yarin

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7768

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10839&pm=7768

Problem Statement

    

Quicksort is one of the most well-known sorting algorithms. On average it makes O(N log(N)) element comparisons, although in the worst case the number of comparisons is O(n2). The critical part in Quicksort is the selection of the pivot element. If one knows the details of a specific Quicksort implementation, it is generally possible to exploit this and create an input sequence which will cause that implementation to perform badly. This can for instance be used by malicious users to cause time-outs in critical system components that rely too much on the efficiency of Quicksort.

Given the details of a specific Quicksort algorithm (pseudocode below), your task is to generate a sequence of n distinct integers between 1 and n, inclusive, that causes this Quicksort to reach the largest nesting depth (see examples for further clarifications).

 function quicksort(list q)
     var list less, greater
     if length(q) <= 1  
         return q  
     select a pivot value pivot from q
     for each x in q
         if x < pivot then add x to less
         if x > pivot then add x to greater
     return concatenate(quicksort(less), [pivot], quicksort(greater))

The pivot element selected in the pseudocode will be the median of three elements in q. The relative position of these three elements will be given by the input parameter positions, containing three integers between 0 and 999, inclusive. If the number of elements in q is k, the position (0-indexed) for the three elements that will be considered as pivot elements will thus be (k * positions[x]) / 1000 (rounded down) for each x between 0 and 2, inclusive. The most common pivot selection method is to take the median of the first, the middle and the last element, which would correspond to positions = {0, 500, 999}.

Create a class WorstCaseQuicksort containing the method worstInput which takes as input an int n and a int[] positions and returns a int[] with n distinct integers between 1 and n, inclusive, so that the largest nesting depth is reached. Since there are many such int[]s, return the one that comes first lexicographically (see notes).

 

Definition

    
Class:WorstCaseQuicksort
Method:worstInput
Parameters:int, int[]
Returns:int[]
Method signature:int[] worstInput(int n, int[] positions)
(be sure your method is public)
    
 

Notes

-The relative order of the elements in the lists less and greater in the pseudocode are the same as that in q.
-A int[] A is lexicographically before a int[] B if there exists an integer i such that A[i] < B[i] and A[j] = B[j] for all j < i.
 

Constraints

-n will be between 1 and 1000, inclusive.
-positions will contain exactly 3 elements.
-Each element in positions will be between 0 and 999, inclusive.
 

Examples

0)
    
5
{0,500,999}
Returns: {1, 2, 3, 4, 5 }
Any array with 5 elements where the median of the first, middle and last element is used to pick the pivot element will cause a maximum nesting depth of 3 levels, so we return the lexicographically first sequence.
1)
    
8
{500, 500, 500}
Returns: {1, 3, 5, 7, 8, 6, 4, 2 }
With these values, the middle element (rounded up when there is an odd number of elements) will always be the pivot element. Knowing this, we can create a sequence requiring 8 nesting levels.
2)
    
10
{800, 100, 400}
Returns: {1, 2, 5, 7, 9, 3, 6, 8, 10, 4 }

The top node in the picture below shows the lexicographically first array that causes the maximum recursion depth of 6 levels.

3)
    
30
{800,150,800}
Returns: 
{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24, 26, 27, 28, 29, 30, 25, 20, 15, 10, 5 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

NormalizingTrees

Graph Theory, Greedy, Recursion



Used in:

SRM 348

Used as:

Division I Level Three

Writer:

soul-net

Testers:

PabloGilberto , brett1479 , Cosmin.ro , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7751

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10672&pm=7751

Problem Statement

    

Trees are important data structures in programming. In this problem, you will be given a tree that was constructed from a fully connected undirected acyclic graph with exactly N nodes. First, a distinct number between 0 and N-1, inclusive, was assigned to each node. Then, one of the nodes was selected to be the root of the tree. Finally, each non-root node was assigned its neighbor closest to the root as its parent.

You will be given the tree as a int[], where the i-th element is the parent of the i-th node, or -1 if the i-th node is the root (indices are 0-based). A tree is considered equivalent to this tree if it can be constructed from the same original graph using the method described above. This means you can renumber the nodes and select a different node as the root (see examples for clarification). Return a int[] containing the equivalent tree that comes first lexicographically. A int[] a1 comes before int[] a2 lexicographically if a1 has a smaller value at the first element where they differ.

 

Definition

    
Class:NormalizingTrees
Method:normalize
Parameters:int[]
Returns:int[]
Method signature:int[] normalize(int[] tree)
(be sure your method is public)
    
 

Constraints

-tree will contain between 1 and 50 elements, inclusive.
-Each element of tree will be between -1 and N-1, inclusive, where N is the number of elements in tree.
-Exactly one element of tree will be -1.
-tree will represent a connected acyclic graph.
 

Examples

0)
    
{2,0,-1,4,2,4}
Returns: {-1, 0, 0, 0, 1, 4 }
This is the original drawing (with 2 as the root):
    2
   / \
  0   4
 /   / \
1   3   5
The renumbering gives this:
    1
   / \
  4   0
 /   / \
5   2   3
and taking the new 0 as the root gives the answer:
   0
 / | \
1  2  3
|
4
|
5
1)
    
{-1,0,1,2,3}
Returns: {-1, 0, 0, 1, 2 }
This is a simple path of length 5. Selecting the middle node as root and renumbering gives the lexicographically first representation.
2)
    
{3,3,3,4,-1,3}
Returns: {-1, 0, 0, 0, 0, 0 }
This tree has the shape of a star (one center node with 5 nodes connected to it).
3)
    
{10,9,6,10,6,9,7,-1,9,7,7,10,6}
Returns: {-1, 0, 0, 0, 0, 1, 1, 5, 5, 5, 6, 6, 6 }
4)
    
{-1, 0, 0, 0, 0, 1, 1, 5, 5, 5, 6, 6, 6}
Returns: {-1, 0, 0, 0, 0, 1, 1, 5, 5, 5, 6, 6, 6 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GuitarConcert

Search



Used in:

SRM 366

Used as:

Division I Level Two

Writer:

jthread

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7747

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10781&pm=7747

Problem Statement

    

You are a guitar player and you want to play a concert. Unfortunately, you don't have any good guitars left, so you need to buy some new guitars. You are given a String[] guitarNames, the i-th element of which is the name of the i-th guitar that is available for purchase.



You have a list of songs that you would like to play at the concert. Certain songs cannot be played with certain guitars because they will sound weird, so you might not be able to play the entire concert with just one guitar. You are given a String[] guitarSongs, where the j-th character of the i-th element is 'Y' if the j-th song can be played on the i-th guitar, and 'N' otherwise.



You want your concert to be as long as possible, so your main goal is to play as many of the songs as possible (you can only play each song at most once). You also want to save your money, so you want to buy the least number of guitars required to play that maximum number of songs. Return a String[] containing the names of the guitars you should buy in alphabetical order. If there are multiple possible return values, return the one among them that comes first lexicographically. A String[] s1 comes before String[] s2 lexicographically if s1[i] comes before s2[i] alphabetically, where i is the first position at which they differ.

 

Definition

    
Class:GuitarConcert
Method:buyGuitars
Parameters:String[], String[]
Returns:String[]
Method signature:String[] buyGuitars(String[] guitarNames, String[] guitarSongs)
(be sure your method is public)
    
 

Constraints

-guitarNames will contain between 1 and 10 elements, inclusive.
-guitarSongs will contain the same number of elements as guitarNames.
-Each element of guitarSongs will contain between 1 and 50 characters, inclusive.
-Each element of guitarSongs will contain the same number of characters.
-Each element of guitarSongs will contain only the uppercase letters 'Y' or 'N'.
-Each element of guitarNames will contain between 2 and 50 characters, inclusive.
-Each element of guitarNames will contain only uppercase letters ('A' - 'Z').
-All elements of guitarNames will be distinct.
 

Examples

0)
    
{"GIBSON","FENDER", "TAYLOR"}
{"YNYYN", "NNNYY", "YYYYY"}
Returns: {"TAYLOR" }
You can play all the songs on the TAYLOR guitar.
1)
    
{"GIBSON", "CRAFTER", "FENDER", "TAYLOR"}
{"YYYNN", "NNNYY", "YYNNY", "YNNNN"}
Returns: {"CRAFTER", "GIBSON" }
You can play all the songs, but you need 2 guitars to do it.
2)
    
{"AB", "AA", "BA"}
{"YN", "YN", "NN"}
Returns: {"AA" }
You can only play the first song, so you buy guitar AA because it comes before AB alphabetically.
3)
    
{"FENDER", "GIBSON", "CRAFTER", "EPIPHONE", "BCRICH"}
{"YYNNYNN", "YYYNYNN", "NNNNNYY", "NNYNNNN", "NNNYNNN"}
Returns: {"BCRICH", "CRAFTER", "GIBSON" }
4)
    
{"GIBSON","FENDER"}
{"NNNNNNNNNNNNNNNNNNNNNNNNN", "NNNNNNNNNNNNNNNNNNNNNNNNN"}
Returns: { }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DayTrader

Simple Math



Used in:

TCO07 Finals

Used as:

Division I Level One

Writer:

legakis

Testers:

PabloGilberto , Olexiy , Mike Mirzayanov , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7721

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10843&pm=7721

Problem Statement

    

The New York Stock Exchange is open for 390 minutes a day, from 9:30am until 4:00pm. During this time, you can buy and sell shares of companies listed on the exchange. Given a graph of how the share prices of two companies fluctuate in one day, calculate the highest amount of money you could possibly earn.

You begin the day with $1000. At any time, you can buy shares of either company at a cost of the number of shares you are buying times the current share price. Similarly, at any time you can sell shares you own of either company for a price of the number of shares you are selling times the current share price. You are not limited to buying or selling whole numbers of shares. You may never spend more money than you have, nor may you sell more shares than you own. Assume you pay no fees or commission on any purchase or sale.

The share price for a company will be given as a pair of int[]s, the first giving a list of times, and the second giving the corresponding share price at each of those times. The times will always be in ascending order, the first time will always be 0, and the last time will always be 390. To compute the stock price between two adjacent times in the arrays, linearly interpolate between the two prices. The times and prices of the first stock ("stock A") are given by timeA and priceA, and the times and prices of the second stock ("stock B") are given by timeB and priceB.

For example, given the following input arrays:

    timeA  = { 0,  60, 150, 270, 390 }
    priceA = { 60, 80, 40,  40,  60 }
    timeB  = { 0,  180, 300, 390 }
    priceB = { 40, 20,  70,  80 }

stock A is shown in red and stock B is shown in blue in the figure below.



In this example, you would make the most money by spending your entire $1000 to buy 16 2/3 shares of stock A for $60 each at time 0. One hour later at time 60, you should sell all your shares at $80 each, receiving 1333 1/3 dollars. You would hold on to your money until time 180, and then spend it all on 66 2/3 shares of stock B. At time 300, you would sell these shares for $70 each (4666 2/3 dollars) and immediately buy as many shares of stock A as you can afford. The price of stock A at time 300 is $45 (1/4 of the way between $40 and $60), so you can afford 103 19/27 shares. You would then sell these at the end of the day for $60, for a total of 6222 2/9 dollars, giving you earnings of about $5222.22 over your initial $1000.

 

Definition

    
Class:DayTrader
Method:earnings
Parameters:int[], int[], int[], int[]
Returns:double
Method signature:double earnings(int[] timeA, int[] priceA, int[] timeB, int[] priceB)
(be sure your method is public)
    
 

Notes

-Your return value must have an absolute or relative error less than 1e-9.
 

Constraints

-timeA, priceA, timeB, and priceB will each contain between 2 and 50 elements, inclusive.
-timeA and priceA will contain the same number of elements.
-timeB and priceB will contain the same number of elements.
-The first element of timeA and timeB will be 0.
-The last element of timeA and timeB will be 390.
-The elements of timeA and timeB will be strictly ascending.
-Each element of priceA and priceB will be between 10 and 100, inclusive.
 

Examples

0)
    
{ 0, 390 }
{ 25, 50 }
{ 0, 390 }
{ 10, 30 }
Returns: 2000.0
Stock A doubles in value throughout the day, while stock B triples. If you buy stock B at time 0 and sell at time 390, you can earn $2000.
1)
    
{ 0, 50, 390 }
{ 80, 65, 20 }
{ 0, 310, 390 }
{ 12, 12, 11 }
Returns: 0.0
Neither stock ever goes up in value, so you cannot earn any money today.
2)
    
{ 0, 60, 150, 270, 390 }
{ 60, 80, 40, 40, 60 }
{ 0, 180, 300, 390 }
{ 40, 20, 70, 80 }
Returns: 5222.222222222223
This is the example from the problem statement.
3)
    
{ 0, 390 }
{ 10, 20 }
{ 0, 100, 101, 390 }
{ 100, 10, 100, 10 }
Returns: 18959.266802443988
4)
    
{0, 100, 200, 300, 390 } 
{ 10, 11, 14, 19, 26 }
{ 0, 50, 150, 250, 350, 390 }
{ 10, 10, 12, 16, 22, 29 }
Returns: 2403.157552083335

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RaceOrdering

Dynamic Programming, Graph Theory, Simple Math



Used in:

SRM 371

Used as:

Division I Level Three

Writer:

bmerry

Testers:

PabloGilberto , Yarin , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7703

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10787&pm=7703

Problem Statement

    You are trying to predict the outcome of a race between n runners, numbered from 0 to n - 1.You are given two int[]s, first and second. It is guaranteed that for all i, the runner numbered first[i] will always beat the runner numbered second[i]. Determine how many final orderings are possible, modulo 1,000,003. If the information is contradictionary, return 0. Runners are never tied.
 

Definition

    
Class:RaceOrdering
Method:countOrders
Parameters:int, int[], int[]
Returns:int
Method signature:int countOrders(int n, int[] first, int[] second)
(be sure your method is public)
    
 

Constraints

-n will be between 1 and 30, inclusive.
-first and second will each contain between 0 and 15 elements, inclusive.
-first and second will contain the same number of elements.
-Each element of first and second will be between 0 and n - 1, inclusive.
-first[i] does not equal second[i] for all i between 0 and m - 1, inclusive, where m is the number of elements in first and second.
 

Examples

0)
    
3
{1}
{2}
Returns: 3
Contestant 1 beat contestant 2, so the valid orders are 012, 102 and 120.
1)
    
4
{0, 0}
{1, 2}
Returns: 8
Contestant 0 beat contestants 1 and 2, but there is no information on contestant 3. The valid orderings are 3012, 3021, 0312, 0321, 0132, 0231, 0123 and 0213.
2)
    
10
{1, 2, 3}
{2, 3, 1}
Returns: 0
There is no way to satisfy this cycle.
3)
    
30
{}
{}
Returns: 90317

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

HeightRound

Dynamic Programming



Used in:

SRM 346

Used as:

Division I Level Two

Writer:

soul-net

Testers:

PabloGilberto , brett1479 , Yarin , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7682

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10670&pm=7682

Problem Statement

    

There are several people that will sit around the same table in a circular fashion. Since all these people are very self-conscious about their height, you don't want to sit any short person next to a tall one. To formalize this, we want to minimize the maximum height difference between 2 adjacent persons.

You will be given the heights of the people as a int[]. Return a int[] with the height of each individual in clockwise order of a seating arrangement that follows the above rule. If there are several solutions, return the lexicographically first one.

 

Definition

    
Class:HeightRound
Method:getBestRound
Parameters:int[]
Returns:int[]
Method signature:int[] getBestRound(int[] heights)
(be sure your method is public)
    
 

Constraints

-heights will contain between 3 and 50 elements, inclusive.
-Each element of heights will be between 1 and 1000, inclusive.
 

Examples

0)
    
{1,2,3,4}
Returns: {1, 2, 4, 3 }
It's better to separate the tallest and shortest people in the round. All solutions with 1 and 4 separated are equivalent, so we choose the lexicographically first one.
1)
    
{1000,500,1}
Returns: {1, 500, 1000 }
In a round of only 3 persons, everybody is next to everyone else, so we only have to return the lexicographically first representation.
2)
    
{1,3,4,5,7}
Returns: {1, 3, 5, 7, 4 }
3)
    
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
Returns: 
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RaceTrack

Greedy, Search



Used in:

TCO07 Round 1C

Used as:

Division I Level Two

Writer:

Mike Mirzayanov

Testers:

PabloGilberto , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7670

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10743&pm=7670

Problem Statement

    

A race track is represented as a line segment. You are given its length, and a int[] pos containing the positions where judges may be located. Each element of pos is the distance from the starting point of the race track. The elements of pos are given in strictly increasing order (pos[i] < pos[i+1]).

You are given an int judges, the number of judges in the next competition. You must assign the judges to positions such that the distance between the two closest judges is as large as possible. Return a String containing exactly n characters, where n is the number of elements in pos. The i-th character should be '1' (one) if there is a judge assigned to the i-th position, and '0' (zero) if there is not. The judges are lazy and don't want to go far from the starting point, so if there are multiple optimal solutions, return the one that comes latest lexicographically.

 

Definition

    
Class:RaceTrack
Method:judgePositions
Parameters:int, int, int[]
Returns:String
Method signature:String judgePositions(int length, int judges, int[] pos)
(be sure your method is public)
    
 

Constraints

-length will be between 1 and 1000000, inclusive.
-pos will contain between 2 and 50 elements, inclusive.
-Each element of pos will be greater than the previous, if it exists.
-Each element of pos will be between 0 and length, inclusive.
-judges will be between 2 and number of elements in pos, inclusive.
 

Examples

0)
    
11
3
{0, 5, 10, 11}
Returns: "1110"
Another solution that maximizes the distance between the two closest judges is "1101", but it is not the lexicographically latest.
1)
    
11
2
{0, 5, 10, 11}
Returns: "1001"
The distance between the two judges should be as large as possible.
2)
    
11
4
{0, 5, 10, 11}
Returns: "1111"
The judges do not have any choice.
3)
    
1000
5
{6, 9, 33, 59, 100, 341, 431, 444, 565, 857}
Returns: "1000010111"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DateFormat

Simulation, String Parsing



Used in:

SRM 354

Used as:

Division I Level One , Division II Level Two

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Yarin , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7654

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10711&pm=7654

Problem Statement

    

In the US, dates are usually written starting with the month, but in Europe, they are usually written starting with the day. So, January 16 will be written as "01/16" in the US and as "16/01" in Europe.

You have a list of dates for the next year and it is known that the given dates are listed in strictly increasing order. Unfortunately, the list was populated by different people and it can contain dates in both formats. You want to convert all dates into the US format.

You will be given a String dateList. First, you should concatenate all elements of dateList and consider it as one String. The conjoint dateList will contain a space-separated list of the dates. Each date will be in the form "XX/XX" (quotes for clarity), where each X is a digit. Convert the dates (without changing the order of the list) so that each date is in the US format and the list is in strictly increasing order. Note that in the original list, the format in which certain dates were written might be ambiguous. You may interpret those dates as being in either format as long as the final list is in strictly increasing order. Return the result as a single String in the same format as the original. If there are several solutions possible return one that comes first lexicographically. If it is impossible to obtain a strictly increasing list of dates, return an empty String.

 

Definition

    
Class:DateFormat
Method:fromEuropeanToUs
Parameters:String[]
Returns:String
Method signature:String fromEuropeanToUs(String[] dateList)
(be sure your method is public)
    
 

Notes

-Next year is 2008, a leap year. So, February 29 is a valid date.
 

Constraints

-dateList will contain between 1 and 50 elements, inclusive.
-Each element of dateList will contain between 1 and 50 characters, inclusive.
-The conjoint dateList will contain a single space separated list of dates without leading or trailing spaces.
-Each date in dateList will be in the form "XX/XX" (quotes for clarity), where each X is a digit.
-Each date in dateList will represent a valid date in either US format or European format.
 

Examples

0)
    
{"16/01"}
Returns: "01/16"
The example from the problem statement.
1)
    
{"02/01 08/02 08/02 21/09 06/11"}
Returns: "01/02 02/08 08/02 09/21 11/06"
The first date is either January 2 or February 1.

The second date is either February 8 or August 2.

The third date is either February 8 or August 2.

The fourth date is definitely September 21.

The fifth date is either June 11 or November 06.

There are two ways to interpret these dates in strictly increasing order: "01/02 02/08 08/02 09/21 11/06" and "02/01 02/08 08/02 09/21 11/06". The first variant comes earlier lexicographically.
2)
    
{"08/02 08/02 03/04"}
Returns: ""
3)
    
{"2", "9/02", " 08/", "03 01/08"}
Returns: "02/29 03/08 08/01"
4)
    
{"17/01 05/05 03/07 07/24 23/09 09/30 01/11 11/11"}
Returns: "01/17 05/05 07/03 07/24 09/23 09/30 11/01 11/11"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CableDonation

Graph Theory, Greedy



Used in:

TCO08 Qual 3

Used as:

Division I Level Two

Writer:

legakis

Testers:

PabloGilberto , vorthys , Olexiy , misof , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7643

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12058&pm=7643

Problem Statement

    

A local charity is asking for donations of Ethernet cable. You realize that you probably have a lot of extra cable in your house, and make the decision that you will donate as much cable as you can spare.

You will be given a String[] lengths indicating the length (in meters) of cables between each pair of rooms in your house. You wish to keep only enough cable so that every pair of rooms in your house is connected by some chain of cables, of any length. The jth character of lengths[i] gives the length of the cable between rooms i and j in your house. A value of '0' (zero) indicates no cable, values of 'a' through 'z' indicate lengths of 1 through 26, and values of 'A' through 'Z' indicate lengths of 27 through 52.

If both the jth character of lengths[i] and the ith character of lengths[j] are greater than 0, this means that you have two cables connecting rooms i and j, and you can certainly donate at least one of them. If the ith character of lengths[i] is greater than 0, this indicates unused cable in room i, which you can donate without affecting your home network in any way.

You are not to rearrange any cables in your house; you are only to remove unnecessary ones. Return the maximum total length of cables (in meters) that you can donate. If any pair of rooms is not initially connected by some path, return -1.

 

Definition

    
Class:CableDonation
Method:cable
Parameters:String[]
Returns:int
Method signature:int cable(String[] lengths)
(be sure your method is public)
    
 

Constraints

-lengths will contain between 1 and 50 elements, inclusive.
-The length of each element of lengths will be equal to the number of elements in lengths.
-Each character in lengths will be a letter ('a'-'z', 'A'-'Z') or '0' (zero).
 

Examples

0)
    
{ "abc",
  "def",
  "ghi" }
Returns: 40
You can part with the following cables:
  • length 1 in room 0
  • length 5 in room 1
  • length 9 in room 2
  • length 4 between rooms 0 and 1
  • length 7 between rooms 0 and 2
  • length 6 between rooms 1 and 2
  • length 8 between rooms 1 and 2
for a total of 40 meters.
1)
    
{ "a0",
  "0b" }
Returns: -1
The two rooms are not connected.
2)
    
{ "0X00",
  "00Y0",
  "0000",
  "00Z0" }
Returns: 0
You have no unnecessary cable.
3)
    
{ "Az",
  "aZ" }
Returns: 105
4)
    
{ "0top",
  "c0od",
  "er0o",
  "pen0" }
Returns: 134

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MinimumTours

Graph Theory, Search



Used in:

SRM 411

Used as:

Division I Level Three

Writer:

hken

Testers:

PabloGilberto , Olexiy , misof , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7620

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12183&pm=7620

Problem Statement

    Little Bonnie has taken a vacation to Ha Long Bay. There are a few thousand stone islands in the bay, making it one of the most beautiful natural scenes in Vietnam. Bonnie is so impressed by this fact that she has decided to visit all of the islands.



She bought a map of all the islands in the bay. This map is given in the String[] islandMap, which is a two-dimensional matrix where each cell is either '.' or lowercase 'x'. '.' cells represent sea and 'x' cells represent land. Two cells are connected if they have a point in common, so each cell may connect to at most 8 other cells. An island is defined as a maximal connected group of 'x' cells. A trip between two islands is defined as a connected group of '.' cells where, for each of the two islands, there is at least one '.' cell in the trip which is connected to a cell in that island. If there is no such connected group of '.' cells between two islands, then there is no trip between them. Note that an island can be nested inside another island.



A tour is a sequence of islands where there is a trip between every pair of consecutive islands in the sequence. Little Bonnie wants to visit every island exactly once, and she wants to do this using the minimum possible number of tours. Return the number of tours she will have to take.
 

Definition

    
Class:MinimumTours
Method:getMinimumTours
Parameters:String[]
Returns:int
Method signature:int getMinimumTours(String[] islandMap)
(be sure your method is public)
    
 

Notes

-It is possible for a tour to have only one island.
-Bonnie cannot leave the mapped area at any time.
-It is assumed that Bonnie has another way to travel from the last island of one tour to the first island of another tour, so you don't have to take this into account when solving the problem.
 

Constraints

-islandMap will contain between 1 and 50 elements, inclusive.
-Each element of islandMap will contain between 1 and 50 characters, inclusive.
-Each element of islandMap will contain the same number of characters.
-Each character in islandMap will be either '.' or lowercase 'x'.
-There will be at least one island in the map.
 

Examples

0)
    
{
"..x..x..x..",
"..x..x..x..",
"..x..x..x..",
"..x..x..x.."
}
Returns: 1
Only one tour is needed. Bonnie can just go from the leftmost island through the middle one to the rightmost island. Or she can choose to go in the reverse way.
1)
    
{
"x....x....x",
".....x.....",
".....x.....",
".....x.....",
"xxxxxxxxxxx",
".....x.....",
".....x.....",
".....x.....",
"x....x....x"
}
Returns: 3
At least three tours are required to cover the five islands. One possible set of three tours is to go from the small island in the top-left corner through the big cross-shaped island to the top-right island, and each of the two other islands makes up a one-island tour.
2)
    
{
"x....x....x",
".....x.....",
".....x.....",
"....x.x....",
"xxxx...xxxx",
"....x.x....",
".....x.....",
".....x.....",
"x....x....x"
}
Returns: 1
There is always a trip between any two islands. So only one tour is enough to visit all five islands.
3)
    
{
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"x............................x",
"x..xxxxxxxxxx....xxxxxxxxxx..x",
"x..x........x....x........x..x",
"x..x..xxxx..x....x.xxxxxx.x..x",
"x..x........x....x.x....x.x..x",
"x..xxxxxxxxxx....x.x.x..x.x..x",
"x................x.x....x.x..x",
"x................x.xxxxxx.x..x",
"x..xxxxxxxxxx....x........x..x",
"x..x........x....x........x..x",
"x..x..xxxx..x....x.xxxxxx.x..x",
"x..x........x....x........x..x",
"x..xxxxxxxxxx....xxxxxxxxxx..x",
"x............................x",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
Returns: 2
An island can be nested inside another one. And two tours are needed in this example.
4)
    
{
"xxxxxxxxxxxxx....xxxxxxxxxxxxxxxxxxxxxx",
"x...........x....x.....................",
"x.xxxxxxxxx.x....x.xxxxxxxxxxxxxxxxxxx.",
"x.x.......x.x....x.x.................x.",
"x.x.xxxxx.x.x....x.x.xxxxxxxxxxx.....x.",
"x.x...x...x.x....x.x.x..........x....x.",
"x.x...x...x.x....x.x.x.xxx..xxx...x..x.",
"x.x.......x.x....x.x.x.x....x..x..x..x.",
"x.xxxxxxxxx.x....x.x.x.xxx..x..x..x..x.",
"x...........x....x.x.x.x....x..x..x..x.",
"xxxxxxxxxxxxx....x.x.x.xxx..xxx...x..x.",
"x................x.x.x......xx....x..x.",
"x................x.x.x......x.x...x..x.",
"x................x.x.x......x..x..x..x.",
"x................x.x.x...........x...x.",
"x................x.x.xxxxxxxxxxxx....x.",
"x................x.x.................x.",
"x................x.xxxxxxxxxxxxxxxxxxx.",
"x................x.....................",
"x................xxxxxxxxxxxxxxxxxxxxxx"
}
Returns: 1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

StarsInGraphs

Dynamic Programming, Graph Theory, Math, Search



Used in:

SRM 350

Used as:

Division I Level Two

Writer:

Xixas

Testers:

PabloGilberto , brett1479 , Olexiy , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7593

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10674&pm=7593

Problem Statement

    You are given the adjacency matrix of a directed graph as a String[] adjacencyMatrix. The j-th character of the i-th element of adjacencyMatrix will be '1' if there is an edge going from the i-th vertex to the j-th, or '0' otherwise. A star in a directed graph is defined as follows: it is comprised of a central vertex and at least three distinct edges emanating from it, which we will call the rays of the star. The number of rays in a star is not bounded; the only restriction is that there must be at least 3 of them. The number of distinct stars for which a vertex V is central will be called the star number of V. For example, if V has 5 edges emanating from it then its star number is 16 = 10 + 5 + 1 since it is central for 10 stars with 3 rays, 5 stars with 4 rays, and 1 star with 5 rays. We will call a path in our graph starry if it satisfies two conditions:
  • Each vertex belonging to the path has a non-zero star number not exceeding C.
  • Given two subsequent vertices Vi and Vi+1 in the path the star number of Vi+1 is not less than the star number of Vi.
Given the directed graph in the form of its adjacency matrix return the number of vertices in the longest starry path it contains. If there is a starry path of infinite length in the graph return -1. If there are no starry paths (all vertices have star numbers either 0 or greater than C) return 0.
 

Definition

    
Class:StarsInGraphs
Method:starryPaths
Parameters:String[], int
Returns:int
Method signature:int starryPaths(String[] adjacencyMatrix, int C)
(be sure your method is public)
    
 

Notes

-Two stars are considered distinct if either their central vertices are distinct or the sets of rays are distinct.
 

Constraints

-adjacencyMatrix will contain between 2 and 50 elements, inclusive.
-The number of characters in each string of the adjacencyMatrix will be equal to the total number of elements in adjacencyMatrix.
-Every character of each element of adjacencyMatrix will be either '0' (zero) or '1' (one).
-The i-th character of the i-th element of adjacencyMatrix will be '0'.
-C will be between 1 and 109, inclusive.
 

Examples

0)
    
{"01110",
 "10111",
 "00000",
 "00000",
 "00000"}
1000
Returns: 2
The starry path 0 -> 1 is the longest one. Vertex 0 has star number 1, vertex 1 has star number 5, and all other vertices have star numbers 0.
1)
    
{"01011",
 "00111",
 "10011",
 "00000",
 "00000"}
1
Returns: -1
Vertices 0, 1, and 2 have star numbers 1 and form a cycle, thus we have an infinite starry path.
2)
    
{"0111",
 "0000",
 "0000",
 "0000"}
1
Returns: 1
This time the longest starry path consists of a single vertex.
3)
    
{"01111",
 "00000",
 "00000",
 "00000",
 "00000"}
4
Returns: 0
Vertex 0 has star number 5 and the rest of the vertices have a zero star number, and thus none of them can appear in a starry path.
4)
    
{"010001100",
 "001001100",
 "000101110",
 "000010111",
 "000001111",
 "010000000",
 "000110000",
 "000100001",
 "100001000"}
10
Returns: 5

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BagsQuiz

Graph Theory, Simulation, String Parsing



Used in:

SRM 350

Used as:

Division II Level Three

Writer:

Xixas

Testers:

PabloGilberto , brett1479 , Olexiy , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7587

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10674&pm=7587

Problem Statement

    We have n bags numbered from 1 to n. Each bag can contain bags in its interior, which themselves can contain more bags. For the purposes of this problem, bag i is said to be inside bag j if and only if bag i is immediately contained in bag j. For example, if bag 1 contains bag 2, which contains bag 3, then bag 3 is inside bag 2, but it is not inside bag 1. All bags are initially empty and lying on the floor. We will perform a sequence of actions, each of which is one of the following types:

"PUT i INSIDE j" - Put bag i inside bag j.  Both bag i and bag j must currently be on the floor for this action to be valid.

"SET i LOOSE" - Remove all the bags currently inside bag i and place them on the floor.  Bag i must currently be on the floor for this action to be valid.

"SWAP i WITH j" - Swap the contents of bag i with the contents of bag j (i.e., take all the bags that are inside bag i and put them inside bag j, and vice versa).  Both bag i and bag j must currently be on the floor for this action to be valid.


The final configuration of bags is said to be proper if no bag lies inside a bag with a smaller number.  Given n, the number of bags, and actions, the sequence of actions to perform on the bags, determine if the final configuration is proper.  If so, return the number of bags that are on the floor in the final configuration.  If it is not proper or if any of the actions are invalid, return -1 instead. See examples for further clarification.
 

Definition

    
Class:BagsQuiz
Method:checkIfProper
Parameters:int, String[]
Returns:int
Method signature:int checkIfProper(int n, String[] actions)
(be sure your method is public)
    
 

Constraints

-n will be between 1 and 50, inclusive.
-actions will contain between 0 and 50 elements, inclusive.
-Each element of actions will be formatted as "PUT i INSIDE j" (where i and j are two distinct integers between 1 and n, inclusive, with no leading zeroes), "SET i LOOSE" (where i is an integer between 1 and n, inclusive, with no leading zeroes), or "SWAP i WITH j" (where i and j are two distinct integers between 1 and n, inclusive, with no leading zeroes). All quotes for clarity only.
 

Examples

0)
    
2
{"PUT 1 INSIDE 2"}
Returns: 1
Bag 1 is put inside bag 2 so only 1 bag remains on the floor.
1)
    
2
{"PUT 1 INSIDE 2", "SET 2 LOOSE"}
Returns: 2
No effect on the initial configuration.
2)
    
2
{"PUT 2 INSIDE 1"}
Returns: -1
This time the obtained configuration is improper since bag 2 lies inside a bag with a smaller number.
3)
    
4
{"PUT 3 INSIDE 2", "SWAP 4 WITH 2", "PUT 2 INSIDE 4", "SET 1 LOOSE"}
Returns: 2
4)
    
3
{"PUT 1 INSIDE 2", "PUT 3 INSIDE 1"}
Returns: -1
We can not perform the last command since the bag 1 is not on the floor.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ImageTraders

Dynamic Programming, Graph Theory



Used in:

SRM 430

Used as:

Division II Level Three

Writer:

Janq

Testers:

PabloGilberto , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7583

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13521&pm=7583

Problem Statement

    There is a community of art lovers who meet from time to time and trade images with each other. Each image transaction must obey the following rules:
  1. The price at which the image is sold must be greater than or equal to the price at which it was bought.
  2. No trader is allowed to buy the same image more than once.
A new image has just appeared on the market. Trader 0 bought it from an unknown artist for the price of '0', and he is now ready to trade it among his fellow art lovers. You are given a String[] price, where the j-th character of the i-th element is a digit representing the price at which trader j will buy the image from trader i. '0' is the lowest price, and '9' is the highest. Assuming all transactions obey the rules mentioned above, determine the longest possible sequence of transactions involving the new image. After all the transactions are done, return the number of people who have owned the image at some point in time, including both the final owner and trader 0.
 

Definition

    
Class:ImageTraders
Method:maxOwners
Parameters:String[]
Returns:int
Method signature:int maxOwners(String[] price)
(be sure your method is public)
    
 

Constraints

-price will contain exactly N elements, where N is between 2 and 15, inclusive.
-Each element of price will contain exactly N characters.
-Each element of price will contain only digits ('0'-'9').
 

Examples

0)
    
{
"01",
"10"
}
Returns: 2
Trader 0 can sell the image to trader 1 for the price of '1'. Both traders were owners of the image, so the answer is 2.
1)
    
{
"022",
"101",
"110"
}
Returns: 2
We have 3 traders here. Trader 0 can sell the image to either trader 1 or trader 2 for the price of '2'. In both cases, the buyer would have to sell the image for a price of at least '2', which is impossible. Therefore, the maximal number of owners is 2.
2)
    
{
"01231",
"00231",
"00031",
"00002",
"00000"
}
Returns: 4
Here the image can have 4 owners:
  • Trader 0 sells the image to trader 1 for the price of '1'.
  • Trader 1 sells the image to trader 2 for the price of '2'.
  • Trader 2 sells the image to trader 3 for the price of '3'.
3)
    
{
"15555",
"11111",
"15111",
"11111",
"11111"
}
Returns: 3
Trader 0 can sell the image to trader 2 for the price of '5'. Then, trader 2 can sell it to trader 1.
4)
    
{
"0100000000",
"0020000000",
"0003000000",
"0000400000",
"0000050000",
"0000006000",
"0000000700",
"0000000080",
"0000000009",
"1111111111"
}
Returns: 10
The image can be traded among all the traders in the following sequence: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

YahtzeeAdversary

Brute Force, Math



Used in:

TCHS07 Gamma 2

Used as:

Division I Level Three

Writer:

timmac

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7563

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10718&pm=7563

Problem Statement

    

In the game of Yahtzee, 5 dice (6 sided) are rolled (and then some of them re-rolled) in an attempt to make one of several formations with the dice. We will introduce a new two-player version of the game in which player one first rolls all five dice, and then player two chooses at least two of the five dice, which the first player must then re-roll. The goal of player two is to minimize the expected score of the first player.

In our version of the game, we are only concerned about four possible results:

  • Yahtzee: All five dice show the same value
  • Large Straight: All five dice form a straight (1,2,3,4,5 or 2,3,4,5,6)
  • Small Straight: Four of the five dice form a straight
  • Full House: Three dice show the same value, and the other two also have the same value (ex. {1, 3, 1, 1, 3} or {2, 2, 2, 2, 2})

You are given a int[] scores indicating how many points each of the four formations is worth. (In order, they are given as Yahtzee, Large Straight, Small Straight, Full House) You are also given a int[] dice, indicating the values shown on each of the five dice after player one has rolled. You should return a int[] indiciating the 0-based indices of the dice that should be selected for re-rolling, to minimize the expected score of player one. If more than one selection of dice produces the same expected score, return the one that comes first lexicographically. (See notes)
 

Definition

    
Class:YahtzeeAdversary
Method:reRollDice
Parameters:int[], int[]
Returns:int[]
Method signature:int[] reRollDice(int[] scores, int[] dice)
(be sure your method is public)
    
 

Notes

-Although a set of five dice may fit the criteria for more than one formation, it can only be scored for one of the formations. The formation of maximum value will be used as the score. (Ex. 1,2,3,4,5 can only count as a small or large straight, but not both at once.)
-A set of five like values, such as {1, 1, 1, 1, 1} is both a Yahtzee and a Full House. The higher score of the two is counted.
-int[] A1 comes before int[] A2 lexicographically if A1 has a lower value in the first position at which they differ.
-To calculate the expected score, multiply the score of each possible outcome by the probability of that outcome, and sum those values together.
 

Constraints

-scores will contain exactly four elements.
-Each element of scores will be between 0 and 10000, inclusive.
-dice will contain exactly five elements.
-Each element of dice will be between 1 and 6, inclusive.
 

Examples

0)
    
{50, 40, 30, 25}
{1, 1, 1, 1, 1}
Returns: {0, 1, 2 }
This is standard Yahtzee scoring. Rerolling four dice instead of just three increases the likelihood of getting a full house or straight. Rerolling three is the best bet. Picking any three of the five (since they are all showing the same value), we choose the three that come first lexicographically.
1)
    
{50, 40, 30, 25}
{1, 2, 3, 4, 5}
Returns: {2, 3 }
Notice that any possible straight we could form (small or large) would contain 3 and 4 in it. Forcing these two to be rerolled is a good move.
2)
    
{50, 40, 30, 25}
{5, 4, 3, 2, 1}
Returns: {1, 2 }
Notice that for this same example (in a different order) it is still those same two values.
3)
    
{10000, 0, 0, 0}
{1, 1, 1, 1, 1}
Returns: {0, 1, 2, 3 }
A Yahtzee is the only thing that can score us any points. Either rerolling all five dice or only four leaves the same odds of landing the Yahtzee, so we choose the lexicographically first possibility.
4)
    
{0, 0, 10000, 0}
{4, 2, 3, 4, 4}
Returns: {1, 2 }
Here, only a straight will be worth any points. Leaving the opponent with three like dice makes it impossible to end up with four dice in a straight. Please note that we must reroll at least 2 dice.
5)
    
{0, 0, 0, 1}
{3, 3, 3, 3, 3}
Returns: {0, 1, 2, 3 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MetroNetwork

Dynamic Programming, Graph Theory



Used in:

SRM 347

Used as:

Division I Level Three

Writer:

StevieT

Testers:

PabloGilberto , brett1479 , Olexiy , lovro

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7541

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10671&pm=7541

Problem Statement

    You live in a big city and need to travel to work every day using the metro rail network. However, the railway lines aren't 100% reliable and occasionally problems with the track lead to a line having to run much slower than usual. You've been in the city for a while, so you know the approximate probabilities of delays happening on each of the lines. Your task is to develop a strategy that minimizes the expected time to get from your starting point to your destination.



When setting out on your journey, you have no way of telling which lines are delayed. Fortunately, the rail company posts information about delayed lines at the stations. However, they are not very good at communicating between stations, so each station will only have information posted about the train lines that pass through that particular station. You will therefore find out whether a line is delayed the first time you arrive in a station through which that line passes. Note that you have to be in the station to read the notice, so you don't gain information about delays by passing through a station on a train without disembarking. If a line is delayed, then the amount of time for the trains to run between adjacent stations on that line is increased by an amount delay. Getting on and off trains also takes a certain amount of time. You may assume that the lines which are delayed do not change throughout the course of the entire journey. Trains run in both directions on all lines, with the journey time being the same in both directions, but to change direction, you have to disembark and reboard. Assume that a delay affects trains in both directions.



Each line is given as the order of stations that the train visits on that line. A line may pass through a station multiple times, but these intersections are not joined. For example, if a train visits stations 0 1 2 3 4 5 2 6 7 in that order and you are at station 0 wishing to get to station 7, you have two options: visit all the stations on the line, or disembark at station 2 and reboard a different train at the later point on the line where it passes through station 2 again. There is no train that visits stations 0 1 2 6 7 without going through stations 3 4 5.



You will be given a String[] lines, where each element will contain a space-separated list of integers representing the stations that the a single line passes through in order, with the jth integer in the ith element being the number of the jth station on that line. The time that the trains take between each station will be described as a space-separated list of integers in a String[] times. The ith element of times describes the ith line in lines, with the jth integer being the time to travel between the jth and j+1th stations on the line. The probability of each line being delayed is given as a percentage in probabilities in the same order as lines. The time to catch or disembark a train is changeTime and the additional time to travel between adjacent stations if a line is delayed is delay.



You should work out the minimum expected journey time to get from station start to station destination and return this time. Return -1.0 if it is not possible to reach station destination from station start.
 

Definition

    
Class:MetroNetwork
Method:minimizeTime
Parameters:int, int, String[], String[], int[], int, int
Returns:double
Method signature:double minimizeTime(int start, int destination, String[] lines, String[] times, int[] probabilities, int changeTime, int delay)
(be sure your method is public)
    
 

Notes

-The return value must be accurate to within an absolute or relative tolerance of 1e-9.
-changeTime includes the time you spend waiting for trains.
-It takes changeTime time to board a train and changeTime time to disembark. For a single journey on a single line, therefore, the cost is 2 * changeTime + journey-time.
-If multiple lines pass through a station, you will find out about delays on all of these lines when you are in the station.
 

Constraints

-lines will contain between 1 and 8 elements, inclusive.
-times and probabilities will contain the same number of elements as lines.
-Each element of lines and times will contain no more than 50 characters.
-Each element of lines will be a space-separated list of integers, without leading zeros, containing at least 2 integers.
-Each integer in lines will be between 0 and 39, inclusive.
-Each element of times will be a space-separated list of integers, without leading zeros, containing exactly 1 fewer integer than the corresponding element of lines.
-Each integer in times will be between 1 and 100, inclusive.
-Each element of probabilities will be between 0 and 100, inclusive.
-changeTime will be between 1 and 100, inclusive.
-delay will be between 1 and 100, inclusive.
-start and destination will be distinct and will correspond to stations in lines.
 

Examples

0)
    
0
7
{"0 1 2 3 4 5 6 7"}
{"2 2 2 2 2 2 2"}
{50}
5
5
Returns: 41.5


This network is shown topologically in the above diagram. In this diagram and all subsequent ones, station numbers are shown in bold numerals and segment times are shown italicized. When there is a possibility of a line being delayed, this segment time is formatted "non-delayed time/delayed time", quotes for clarity.



Here there is a single line, so no choice as to which route to take. If the line is not delayed then the journey time is

5 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 5 = 24

If the line is delayed, the time is

5 + 7 + 7 + 7 + 7 + 7 + 7 + 7 + 5 = 59

For a total expected journey time of

0.5 * 24 + 0.5 * 59 = 41.5
1)
    
0
3
{"0 1","0 2","1 3","2 3"}
{"5","5","5","5"}
{0,0,50,50}
5
20
Returns: 40.0


This network is shown above. Here you have 2 choices: you can either travel to station 1 on line zero, then change to line 2, or travel to station 2 on line 1 and change to line 3. Lines 0 and 1 are never delayed and lines 2 and 3 are delayed 50% of the time. Since you cannot tell from station 0 which of lines 2 and 3, if either, are delayed, and both of the journey times are otherwise the same, you just pick one of the choices at random. You will end up having to travel on a delayed line 50% of the time.
2)
    
0
3
{"0 1","0 2","0 1 3","2 3"}
{"5","5","100 5","5"}
{0,0,50,50}
5
20
Returns: 35.0


This is the same network as example 1, except line 2 has been extended to station 0 (see diagram). The time to travel on the additional segment is way too long for you to ever bother travelling on it, but it means that line 2 passes through station 0, so you know from the start whether or not it is delayed. The optimal strategy is now to consider whether line 2 is delayed from the start at station 0. If it is, then travel to station 1 on line 0 and then to station 3 on line 2. Otherwise you should take the other route via station 2. This strategy ensures that you will only travel on a delayed line if both lines 2 and 3 are delayed (25% probability), thus leading to a reduction in the expected journey time.
3)
    
0
4
{"0 1 2 3","1 3 4","2 4"}
{"10 10 20","100 10","80"}
{0,50,0}
5
100
Returns: 105.0


This network is shown above. Here, the optimal strategy is to travel to station 1 on line 0 and get off purely to check whether line 1 is delayed or not. If it is, then travel to station 2 on line 0, then station 4 on line 2. Otherwise travel to station 3 on line 0 and then to station 4 on line 1.
4)
    
12
9
{"0 30 1 2 3 4 31 5 6 7",
"38 6 8 32 9 33 10 34 11 0 12 13 14 15 16 36 5 38",
"17 39 18 19 5 8 9 20 21",
"17 39 22 16 23 24 3 25 20 21",
"28 9 20 25 2 27 14 17",
"12 13 27 26 24 4 9 28",
"29 10 1 27 15 22 19",
"11 10 2 26 23 16 22 18"}
{"3 3 2 3 2 3 2 2 5",
"2 1 3 4 3 2 4 2 4 5 1 4 4 2 4 5 4",
"2 4 4 2 2 6 2 4",
"2 8 2 1 1 2 3 1 6",
"6 1 2 2 2 2 6",
"1 7 1 2 2 4 8",
"7 2 3 2 2 4",
"4 4 2 2 1 2 9"}
{20,5,15,50,45,5,10,5}
3
10
Returns: 23.228506624999994
5)
    
0
3
{"0 1","2 3"}
{"2","2"}
{50,50}
5
5
Returns: -1.0
There is no route to the destination here.
6)
    
31
8
{"35 38 1 3 4 7 9 10 12 14 16 18 19 20 21 24 25 26"
,"7 10 11 13 15 16 19 22 23 25 26 27 30 33 35 38 1"
,"35 38 1 3 5 6 9 11 13 16 17 19 22 25 26 29 30 32"
,"24 26 28 29 32 34 37 39 1 4 6 8 11 13 16 17 18 19"
,"13 15 17 20 22 25 26 29 30 32 35 37 0 2 3 6 7 8"
,"20 22 24 26 29 31 32 33 36 38 0 3 6 8 9 12 13 14"
,"12 15 16 18 19 21 22 24 25 26 28 30 31 32 33 35"
,"32 34 37 38 39 0 2 4 7 9 12 15 17 20 22 23 24 27"}
{"2 4 9 9 4 4 2 9 7 5 8 3 3 6 7 4 1"
,"1 6 6 8 8 10 7 1 8 10 9 8 9 3 3 2"
,"2 2 7 9 9 1 9 7 9 6 4 4 1 1 10 2 3"
,"10 10 6 5 1 9 9 6 10 5 4 7 5 3 1 2 2"
,"5 1 3 9 2 5 5 6 5 6 3 5 8 8 5 1 6"
,"4 10 4 1 7 1 9 3 5 3 6 9 2 10 3 9 7"
,"9 3 6 6 6 3 5 6 10 10 2 2 5 2 6"
,"1 7 3 6 1 10 2 1 7 4 7 9 7 10 7 3 2"}
{81,5,54,32,6,12,80,38}
4
88
Returns: 56.38865447903488

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FamilyTravel

Dynamic Programming, Graph Theory



Used in:

TCHS07 Beta 1

Used as:

Division I Level Three

Writer:

tywok

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7514

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10705&pm=7514

Problem Statement

    

You just qualified for a programming contest which is held in a very far city. Since your family loves you too much, they decided to come along with you. Of course, your little brother will come also. You will drive from your home city to the city where the contest is being held, possibly stopping at several other cities along the way. The time it takes to get from one city to the next is called an interval. If an interval of your trip is ever longer than the previous interval, your brother will start crying and your parents will have to turn the car around and go back home, forcing you to miss the contest. Therefore, you must plan the trip so that doesn't happen. If there are multiple ways to achieve this, you must choose the one that minimizes the total length of the trip.

You will be given a String[] graph containing the distances between the cities where you may stop. The jth character of the ith element of graph is the distance from the ith city to the jth city. If it's '0' (zero), it means that you cannot go directly from the ith city to the jth city. Characters 'a' to 'z' represent distances of 1 to 26, and characters 'A' to 'Z' represent distances of 27 to 52. You live in city 0 and the contest is being held in city 1. Return the length of the shortest route from city 0 to city 1 that will not make your brother cry. If no such route exists, return -1.

 

Definition

    
Class:FamilyTravel
Method:shortest
Parameters:String[]
Returns:int
Method signature:int shortest(String[] edges)
(be sure your method is public)
    
 

Constraints

-graph will contain between 2 and 50 elements, inclusive.
-Each element of graph will contain exactly n characters, where n is the number of elements in graph.
-Each character in graph will be a '0' (zero), a lowercase letter ('a'-'z') or an uppercase letter ('A'-'Z').
-The jth character of the ith element of graph will be a '0' (zero).
-The jth character of the ith element of graph will be the same as the ith character of the jth element of graph.
 

Examples

0)
    
{"0ze","z0c","ec0"}
Returns: 8
In this case we can go through city 2 with a time of 5 + 3 = 8, instead of the longer direct way of 26.
1)
    
{"0zc","z0e","ce0"}
Returns: 26
You cannot go through city 2 because the intervals of your trip would be 3, and then 5. The second interval is longer than the first interval, so your brother would start crying. Instead, you must take the longer direct route from city 0 to city 1.
2)
    
{"0Zej0","Z0fkh","ef00d","jk00i","0hdi0"}
Returns: 27
3)
    
{"00z00","0000a","z00bb","00b0b","0abb0"}
Returns: 29
4)
    
{"000a", "00a0", "0a0a", "a0a0"}
Returns: 3
Your brother will not cry if several consecutive intervals will be equal.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LandAndSea

Graph Theory, Search



Used in:

SRM 341

Used as:

Division I Level Two , Division II Level Three

Writer:

pure_

Testers:

PabloGilberto , brett1479 , Olexiy , Andrew_Lazarev

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7512

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10665&pm=7512

Problem Statement

    

Bob's father bought him a toy map of islands and seas. The map is a two-dimensional grid where each cell is either 'x' or '.'. A sea is defined as a maximal connected group of '.' cells, where two '.' cells are connected if they are vertically or horizontally adjacent. An island is defined as a maximal connected group of 'x' cells, where two 'x' cells are connected if they are vertically, horizontally, or diagonally adjacent. An island has a level of 0 if it contains no other islands. An island has a level of K+1 if it contains one or more islands and the highest level of a contained island is K. An island A contains island B if A and B are different and, if you start sailing from any point of island B, you won't be able to sail out of island A (you can sail only horizontally and vertically, but not diagonally).

For example, the given map below has 5 islands with level 0 (islands 0 - 4 on the right picture) and one island with level 1 (island 5). Please note that starting at island 3, you can not sail outside island 5 (you can not sail diagonally), but its possible get out of island 1 when starting at island 4.

xxx.x...xxxxx        000.0...11111
xxxx....x...x        0000....1...1
........x.x.x        ........1.4.1
..xxxxx.x...x        ..55555.1...1
..x...x.xxx.x        ..5...5.111.1
..x.x.x...x..        ..5.3.5...1..
..x...x...xxx        ..5...5...111
...xxxxxx....        ...555555....
x............        2............

Given a String[] seaMap, return a int[], where the k-th element is the number of islands of level k. The int[] must contain exactly (m + 1) elements, where m is the highest level of an island in the map.

 

Definition

    
Class:LandAndSea
Method:howManyIslands
Parameters:String[]
Returns:int[]
Method signature:int[] howManyIslands(String[] seaMap)
(be sure your method is public)
    
 

Constraints

-seaMap will contain between 1 and 50 elements, inclusive.
-Each element of seaMap will contain between 1 and 50 characters, inclusive.
-Each element of seaMap will contain the same number of characters.
-Each element of seaMap will contain only '.' and lowercase 'x' characters.
 

Examples

0)
    
{"x"}
Returns: {1 }
1)
    
{
"xxxxx",
"x...x",
"x.x.x",
"x...x",
"xxxxx"
}
Returns: {1, 1 }
2)
    
{
"xxxxx",
"x...x",
"x.x.x",
"x...x",
"xxxxx",
"xxxxx",
"x...x",
"x.x.x",
"x...x",
"xxxxx"
}
Returns: {2, 1 }
3)
    
{
"..",
".."
}
Returns: { }
4)
    
{
"............",
".......xxxx.",
"..xxx.x...x.",
"..x..x..x.x.",
"..x.x.x...x.",
"..xx...xxx.."
}
Returns: {1, 1 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

VegetableGarden

Graph Theory



Used in:

SRM 340

Used as:

Division I Level Three

Writer:

Mike Mirzayanov

Testers:

PabloGilberto , brett1479 , Yarin , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7507

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10664&pm=7507

Problem Statement

    

Your vegetable garden forms a rectangular grid of equal square plots. You've decided to inspect some of your plots. Starting at the top left corner, you will walk through the garden and return back to your starting point. All plots that lie inside the cycle of your path will be considered inspected. You are not allowed to walk inside the plots; you can only walk along their boundaries. Your path must not intersect itself. The boundaries are wide enough that you can walk along the same boundary multiple times without intersecting your own path.

You are given a String[] garden, where the j-th character of the i-th element represents the plot at row i, column j. The plots you would like to inspect are represented by uppercase 'I' characters. '.' characters represent plots you don't care about, and uppercase 'X' characters represent plots you must never inspect. Return a int[] where the i-th element is equal to the length of the shortest path that lets you inspect exactly i+1 plots marked with the letter 'I'. The number of elements in the return value must be equal to the number of 'I's in garden. Note that it is okay for '.' plots to be inspected, but 'X' plots must never be inspected.

 

Definition

    
Class:VegetableGarden
Method:getMinDistances
Parameters:String[]
Returns:int[]
Method signature:int[] getMinDistances(String[] garden)
(be sure your method is public)
    
 

Constraints

-garden will contain between 1 and 50 elements, inclusive.
-Each element of garden will contain only periods ('.'), uppercase 'I's and uppercase 'X's.
-Each element of garden will contain an equal number of characters.
-Each element of garden will contain between 1 and 50 characters, inclusive.
-garden will contain between 1 and 10 characters that are not periods ('.').
 

Examples

0)
    
{"I"}
Returns: {4 }
Walk around the periphery of the plot.
1)
    
{"XX", 
 "XI"}
Returns: {8 }

2)
    
{"III", 
 "IXI",
 "III"}
Returns: {4, 6, 8, 10, 12, 14, 16, 18 }
An example of inspecting 8 plots is below.

3)
    
{"X.I", 
 ".I.", 
 "I.."}
Returns: {8, 10, 14 }
4)
    
{"IIXIIXIXII"}
Returns: {4, 6, 12, 14, 20, 26, 28 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MedievalCity

Graph Theory



Used in:

TCO07 Round 1C

Used as:

Division I Level Three

Writer:

Mike Mirzayanov

Testers:

PabloGilberto , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7506

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10743&pm=7506

Problem Statement

    

A medieval city consists of square blocks, each of equal size, situated on a grid. The blocks form a connected figure with no holes. An example of such a city is shown in the picture below.

The red line shows the boundary of the city. Each block has a danger value that is assigned as follows. Blocks that have the city boundary as a side are called 0-dangerous. Blocks that are adjacent to 0-dangerous blocks and have not yet been assigned a danger value are called 1-dangerous. Two blocks are considered adjacent if they share a side. Blocks that are adjacent to 1-dangerous blocks and have not yet been assigned a danger value are called 2-dangerous blocks, and so on. In the picture above, all 0-dangerous and 1-dangerous blocks are colored dark gray.

We can represent a city as a string of letters 'R', 'L', 'U', 'D' (right, left, up, down) describing a walk along its boundary in the clockwise or counter-clockwise direction. Each letter represents the length of a single block's side. Multiple consecutive equal letters can be written using a simple compression method. An integer K that immediately follows a letter means that the letter is repeated K times. For example, the city in the picture above can be described by the string "LUUR7D4RDLDDDL7UURU2UU". Obviously there can be multiple strings that describe the same city.

You are given a String[] boundary and an int dangerBound. Concatenate all the elements of boundary to get the string description of a city. Return the number of i-dangerous blocks in the city where i <= dangerBound.

 

Definition

    
Class:MedievalCity
Method:getDangerousBlocks
Parameters:String[], int
Returns:int
Method signature:int getDangerousBlocks(String[] boundary, int dangerBound)
(be sure your method is public)
    
 

Constraints

-boundary will contain between 1 and 50 elements, inclusive.
-Each element of boundary will contain between 1 and 50 characters, inclusive.
-The 0-th element of boundary will start with a letter.
-Each element of boundary will contain only the letters 'R', 'L', 'U', 'D', and digits ('0'-'9').
-Each sequences of digits in the concatenation of all the elements of boundary will be an integer without leading zeroes between 1 and 50, inclusive.
-boundary will describe a correct closed boundary that does not touch or intersect itself.
-dangerBound will be between 0 and 10, inclusive.
 

Examples

0)
    
{"LURD"}
0
Returns: 1
This city contains only a single square block.
1)
    
{"LUUR7D4RDLDDDL7UURU2UU"}
1
Returns: 44
The example from the problem statement.
2)
    
{"L50U50R50D50"}
10
Returns: 1716
3)
    
{"L50U50U50U50U50R50D50D50D50D50"}
7
Returns: 3744

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CsCourses

Graph Theory



Used in:

SRM 340

Used as:

Division I Level Two , Division II Level Three

Writer:

Mike Mirzayanov

Testers:

PabloGilberto , brett1479 , Yarin , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7505

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10664&pm=7505

Problem Statement

    

You are studying at a university, and there are many CS courses you can take. The i-th course is described by three values: theoreticalValue[i], practicalValue[i] and expire[i], where i is a 0-based index. Each course lasts one month, and you can not take the i-th course in the expire[i]-th month or later.

For each course i, let tvi = theoreticalValue[i] and pvi = practicalValue[i]. You can take the i-th course only if your theoretical skill is at least tvi-1 and your practical skill is at least pvi-1. If your theoretical skill is less than tvi, it will become tvi after you take the course. Similarly, if your practical skill is less than pvi, it will become pvi after you take the course.

Both your theoretical and practical skills are initially equal to 0, and you can start taking courses in the 0-th month. You can only take one class per month. Your goal is to have your theoretical and practical skills both be greater than or equal to skillBound. You want to achieve this by taking the fewest possible number of courses. Return a int[] containing the courses you should take, in order from earliest to latest. If there is no solution, return an empty int[]. If there are multiple solutions, return the one that comes earliest lexicographically. A int[] a1 comes before a int[] a2 lexicographically if a1 contains a smaller value at the earliest index at which they differ.

 

Definition

    
Class:CsCourses
Method:getOrder
Parameters:int[], int[], int[], int
Returns:int[]
Method signature:int[] getOrder(int[] theoreticalValue, int[] practicalValue, int[] expire, int skillBound)
(be sure your method is public)
    
 

Constraints

-theoreticalValue will contain between 1 and 50 elements, inclusive.
-theoreticalValue, practicalValue and expire will contain the same number of the elements.
-Each element of theoreticalValue will be between 0 and 50, inclusive.
-Each element of practicalValue will be between 0 and 50, inclusive.
-Each element of expire will be between 0 and 50, inclusive.
-skillBound will be between 0 and 50, inclusive.
 

Examples

0)
    
{1}
{1}
{1}
1
Returns: {0 }
1)
    
{1, 2, 1}
{2, 1, 1}
{5, 5, 5}
2
Returns: {2, 0, 1 }
You should take the courses in one of the following orders: {2, 0, 1} or {2, 1, 0}. The first one comes earlier lexicographically.
2)
    
{1, 2, 1}
{2, 1, 1}
{1, 1, 1}
2
Returns: { }
In the 0-th month, the only course you can take is course 2. However, after you complete the course, all three courses will expire.
3)
    
{1, 2, 1}
{2, 1, 1}
{3, 2, 1}
2
Returns: {2, 1, 0 }
4)
    
{1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7}
7
Returns: {0, 1, 2, 3, 4, 5, 6 }
5)
    
{0, 1, 2, 2, 1}
{0, 0, 1, 2, 1}
{9, 9, 9, 9, 9}
2
Returns: {4, 3 }
{0, 1, 2, 3} is a valid order, but we are looking for the fewest number of courses.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WordConnect

Graph Theory



Used in:

Delta Round 1

Used as:

Division I Level Three

Writer:

AdminBrett

Testers:

PabloGilberto , Olexiy , Andrew_Lazarev

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7495

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10706&pm=7495

Problem Statement

    You are given a table of characters. Words are found in table by taking steps up, down, left, or right (up and down refer to row changes, while left and right refer to column changes). The string of letters stepped on during this process is said to be found. If word is found in table, then all of the positions stepped on while finding word are considered pairwise connected. Each occurrence of word that is found is dealt with separately. Connectivity is transitive: if position x connects to y, and position y connects to z, then positions x and z are connected. Return the number of distinct connected components in table (a connected component is a maximal collection of pairwise connected positions). To simplify matters, the characters in word will be distinct.
 

Definition

    
Class:WordConnect
Method:numComponents
Parameters:String, String[]
Returns:int
Method signature:int numComponents(String word, String[] table)
(be sure your method is public)
    
 

Constraints

-word will contain between 1 and 26 lowercase letters ('a'-'z'), inclusive.
-Each character in word will be distinct.
-table will contain between 1 and 50 elements, inclusive.
-Each element of table will contain between 1 and 50 characters, inclusive.
-Each character in table will be a lowercase letter ('a'-'z').
-Each element of table will contain the same number of letters.
 

Examples

0)
    
"top"
{
"toptoptop",
"toptoptop"
}
Returns: 6
There are 6 separate components. Each is numbered below:
111222333 
444555666
1)
    
"top"
{
"aaaaaaaaaaa",
"aaaopopoaaa",
"aaatototaaa",
"aaaopopoaaa",
"aaaaaaaaaaa"
}
Returns: 41
Here there is one large central component, and a surrounding sea of single character components.
2)
    
"topcader"
{
"topcader",
"oaaaaaae",
"paaaaaad",
"caaaaaaa",
"aaaaaaac",
"daaaaaap",
"eaaaaaao",
"redacpot"
}
Returns: 37
A single component lines the outer edge, surrounding a sea of single character components.
3)
    
"topcader"
{
"topcoder",
"oaaaaaae",
"paaaaaad",
"caaaaaaa",
"aaaaaaac",
"daaaaaap",
"eaaaaaao",
"redocpot"
}
Returns: 50
4)
    
"a"
{
"aaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaa"
}
Returns: 220

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CakeParty

Greedy, Math



Used in:

SRM 338

Used as:

Division I Level Three

Writer:

misof

Testers:

PabloGilberto , brett1479 , Olexiy , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7424

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10662&pm=7424

Problem Statement

    

Julianne invited her two friends Michael and Jane to a cake party. When Michael and Jane arrived, they saw that their host had prepared several tables. On each table there was a plate with one of the cakes. Each cake was cut into several pieces.

Not knowing where to start, Michael and Jane decided to play the following game: Players take alternating turns. In each turn the player selects one cake, and takes and eats several pieces of the cake. The player must take and eat at least one piece. The player who eats the last piece of the last cake wins.

However, the host would be really offended if she had the impression that the guests didn't like some of her cakes. Therefore Michael and Jane agreed on one additional rule: Each time a player selects a cake, he or she may only select one of those cakes that have the most pieces remaining.

Michael starts the game and plays optimally. In other words, if there is a strategy that will ensure his win (no matter how Jane plays), he will follow one such strategy. If he finds himself in a position where no strategy can guarantee him winning the game he just makes a valid move. In addition, whenever Michael has more than one move to choose from, he picks the lexicographically smallest one (explained below).

You are given a int[] pieces. The i-th element of pieces is the initial number of pieces of the i-th cake. Return Michael's first move as a String formatted as follows: "CAKE C PIECES P", where C is the zero-based index of the cake he should select and P is the number of pieces he should eat. The numbers C and P must not contain unnecessary leading zeroes. In case there are multiple valid answers return the one where the resulting String is lexicographically smallest.

 

Definition

    
Class:CakeParty
Method:makeMove
Parameters:int[]
Returns:String
Method signature:String makeMove(int[] pieces)
(be sure your method is public)
    
 

Notes

-Ignore the appetite and eating speed of both players. In other words, assume that each of them is able to eat all the cakes in a short amount of time.
-When selecting the correct output, standard string comparison rules apply:

The string A is lexicograpically smaller than the string B if and only if (A is a proper prefix of B) or (there is an integer X such that first X-1 characters of A and B are equal, and the X-th character of A has a smaller ASCII value than the X-th character of B).
-Valid characters ordered by their ASCII values (smallest to largest): space, digits '0'-'9' in this order, letters 'A'-'Z' in this order.
 

Constraints

-pieces will contain between 1 and 50 elements, inclusive.
-Each element of pieces will be between 1 and 2,000,000,000, inclusive.
 

Examples

0)
    
{47}
Returns: "CAKE 0 PIECES 47"
With one cake the game is simple: just take everything.
1)
    
{3,3}
Returns: "CAKE 0 PIECES 1"
Two equally big cakes. This is clearly a losing position for the player to move. Thus we return the lexicographically smallest possible move.
2)
    
{3,5}
Returns: "CAKE 1 PIECES 2"
The winning move is to create the position from the previous example.
3)
    
{1,1,1,1,1,1,1,1,1,1,1,1,1,1}
Returns: "CAKE 0 PIECES 1"
This is an almost deterministic game. The players can not influence the result at all.
4)
    
{3,3,112}
Returns: "CAKE 2 PIECES 110"
This is a winning position, as we can eat the entire last cake and thus create the position from Example 1. However, this is not the only winning move, and there is a lexicographically smaller winning move than the one we described.
5)
    
{3,3,1}
Returns: "CAKE 0 PIECES 1"
Note that we can not eat the last cake now, as it is not one of the largest ones.
6)
    
{4,7,4,7,4,7,4,7,47,47,47,47}
Returns: "CAKE 10 PIECES 1"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DrivingAround

Graph Theory, Simulation



Used in:

SRM 342

Used as:

Division I Level Three

Writer:

Kawigi

Testers:

PabloGilberto , brett1479 , Cosmin.ro , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7412

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10666&pm=7412

Problem Statement

    

You are picking up your friend from the airport, and you just got a call - your friend's flight was delayed! You know exactly how long it will be in minutes before your friend will be ready to get picked up, and you want to drive around until that point in time, arriving at the airport at exactly that time. You want to find out how many ways there are to reach the airport in exactly that amount of time.

The city layout is given as a String[] adj. The ith character of the jth element of adj is '.' if there is no road connecting intersection i to intersection j (both zero-indexed). If there is a road from intersection i to intersection j, the number of minutes it takes to travel that road is given as a number from '1' to '5'. Roads are not necessarily two-way, and two-way roads may not be the same speed both ways. You are at intersection start when you get your friend's call, and the airport is at intersection finish. Calculate the number of ways to get from intersection start to intersection finish in exactly time minutes. Since this number might be rather large, return the answer modulo 1000003.

 

Definition

    
Class:DrivingAround
Method:numberOfWays
Parameters:String[], int, int, int
Returns:int
Method signature:int numberOfWays(String[] adj, int start, int finish, int time)
(be sure your method is public)
    
 

Constraints

-adj will contain between 1 and 10 elements, inclusive.
-The number of characters in each element of adj will be the same as the number of elements in adj.
-Each character in adj will be a '.' or a digit between '1' and '5', inclusive.
-start and finish will each be between 0 and n-1, inclusive, where n is the number of elements in adj.
-The ith character of the ith element of adj will be '.', for all i.
-time will be between 1 and 1000000000, inclusive.
 

Examples

0)
    
{".12",
 "2.1",
 "12."}
0
2
5
Returns: 8
There are 8 ways:
  • 0->1->2->0->1->2
  • 0->1->2->0->2
  • 0->1->2->1->2
  • 0->1->0->1->2
  • 0->1->0->2
  • 0->2->0->1->2
  • 0->2->1->2
  • 0->2->0->2
1)
    
{"....52....",
 "..5.......",
 "..........",
 ".......1..",
 "......42.2",
 "5...4.....",
 ".5...4...1",
 "......5...",
 ".3244.....",
 ".........."}
2
2
10
Returns: 0
2)
    
{"...14....1",
 "......13..",
 ".2...4....",
 "....52.5..",
 "1.3..4....",
 ".3....35.5",
 "4......1.1",
 "..4.4.1.54",
 "....4.11.5",
 "31144.2.4."}
7
2
100
Returns: 316984

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DegreesToRadians

Simple Math



Used in:

SRM 342

Used as:

Division II Level One

Writer:

Kawigi

Testers:

PabloGilberto , brett1479 , Cosmin.ro , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7410

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10666&pm=7410

Problem Statement

    

In some forms of geometry, like the kind used in geographical longitude/latitude measurements, angles are measured in base-60. The base unit is the degree. One degree contains 60 minutes, and one minute contains 60 seconds.

You will be given the measurement of an angle in degrees, minutes, and seconds. Return the given angle in radians. Note that n degrees is equal to n*PI/180 radians.

 

Definition

    
Class:DegreesToRadians
Method:convertToRadians
Parameters:int, int, int
Returns:double
Method signature:double convertToRadians(int degrees, int minutes, int seconds)
(be sure your method is public)
    
 

Notes

-The return value must have an absolute or relative error less than 1e-9.
 

Constraints

-degrees will be between 0 and 359, inclusive.
-minutes will be between 0 and 59, inclusive.
-seconds will be between 0 and 59, inclusive.
 

Examples

0)
    
0
0
0
Returns: 0.0
Zero is zero, in either measurement system.
1)
    
180
0
0
Returns: 3.141592653589793
180 degrees is PI radians.
2)
    
359
59
59
Returns: 6.283180459042776
This is as close to a full circle as it gets.
3)
    
23
30
5
Returns: 0.41017661490272295

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WordSplit

Dynamic Programming



Used in:

TCO07 Round 2

Used as:

Division I Level Two

Writer:

dgoodman

Testers:

PabloGilberto , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7347

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10749&pm=7347

Problem Statement

    Given a string of lowercase letters, I want to split it up into pieces so that the letters in each piece are distinct. I want to form as few pieces as possible. Given theString return a String[] containing the pieces sorted alphabetically.

If more than one way of splitting is minimal, return the sorted sequence of pieces that is first lexicographically. That means that the first element in the sequence that differs is earlier alphabetically.

 

Definition

    
Class:WordSplit
Method:pieces
Parameters:String
Returns:String[]
Method signature:String[] pieces(String theString)
(be sure your method is public)
    
 

Constraints

-theString will contain between 1 and 50 characters, inclusive.
-Each character in theString will be a lowercase letter ('a'-'z').
 

Examples

0)
    
"facetiously"
Returns: {"facetiously" }
No splits are required since all the letters are distinct.
1)
    
"aaaaa"
Returns: {"a", "a", "a", "a", "a" }
This is the only legal split.
2)
    
"aba"
Returns: {"a", "ab" }
We need one split to separate the 'a's. Our choices are a/ba or ab/a. We return the one whose pieces form the earlier sequence lexicographically.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ExpensiveTravel

Graph Theory



Used in:

SRM 335

Used as:

Division I Level Two

Writer:

soul-net

Testers:

PabloGilberto , brett1479 , Cosmin.ro , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7337

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10659&pm=7337

Problem Statement

    

You are lost in a strange land and have to return to the base camp as soon as possible. The land is modeled as a rectangular plane divided into square cells, and each cell can be of one of 9 different types, numbered from 1 to 9. The cost of a cell of type k is exactly 1/k.

To get to the base camp, you can move from each cell to any of its orthogonally adjacent cells (up, down, left or right) instantaneously. The only limitation for the speed of your movements is the cost-per-minute. Time will be divided into one minute intervals, i.e., there is an interval starting at time 0 and ending at time 1, another interval from time 1 to time 2, etc. During each interval of time, the sum of the costs of all the cells you occupy must not exceed 1. If you make an instantaneous move at the exact boundary between two intervals of time, the cells you move between during that move will count toward both intervals' total costs. This means you can never step into or out of a cell of type 1 because any other cell you occupy will always exceed the maximum cost per minute.

You will be given m, a String[] describing the land, where the jth character of the ith element represents the type of the cell at row i, column j (both 1-based). You will also be given startRow, startCol, endRow and endCol, the 1-based indices of the row and column of your starting point and destination, respectively. Return the minimum number of minutes that are needed to get from (startRow, startCol) to (endRow, endCol) following the constraints above. If it's impossible to do so, return -1.

 

Definition

    
Class:ExpensiveTravel
Method:minTime
Parameters:String[], int, int, int, int
Returns:int
Method signature:int minTime(String[] m, int startRow, int startCol, int endRow, int endCol)
(be sure your method is public)
    
 

Constraints

-m will contain between 1 and 50 elements, inclusive.
-Each element of m will contain exactly N characters, where N is an integer between 1 and 50, inclusive.
-Each character of each element of m will be a digit between '1' and '9', inclusive.
-startRow and endRow will each be between 1 and the number of elements in m, inclusive.
-startCol and endCol will each be between 1 and the number of characters in the first element of m, inclusive.
-Either startCol will be different from endCol or startRow will be different from endRow.
 

Examples

0)
    
{"22334"}
1
1
1
5
Returns: 3
During the first minute, you can move 1 cell to the right. The two cells that you occupy during that minute are both of type 2, so the cost is 1/2+1/2=1. In the second minute, you can move 1 more cell to the right. You cannot go any further because 1/2+1/3+1/3 > 1. During the third minute, you can reach your destination by moving 2 cells to the right for a cost of 1/3+1/3+1/4 < 1.
1)
    
{"55",
 "52",
 "55"}
1
2
3
2
Returns: 1
You can step on all 5 5's during the same interval, so you can get there in just 1 minute.
2)
    
{"251",
 "212",
 "122"}
1
1
3
3
Returns: -1
Since it's impossible to step into a cell of type 1, there is no way to get to your destination.
3)
    
{"452232",
 "287979",
 "219872",
 "928234",
 "767676"}
1
6
3
1
Returns: 3
4)
    
{"11"}
1
1
1
2
Returns: -1
5)
    
{"123456789987654321"}
1
2
1
16
Returns: 5

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

VotingBloc

Graph Theory



Used in:

TCO07 Round 3

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

PabloGilberto , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7335

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10751&pm=7335

Problem Statement

    The members of a committee vote 'Yes' or 'No' on various issues. However, some pairs of committee members have formed alliances, promising never to cast opposite votes. No one is willing to vote contrary to her own opinion, so some of the members may need to abstain from voting in order to avoid conflict between allies.

We have devised a method to determine who should abstain. Before each issue is voted on, we randomly assign each committee member an identifying number, 1, 2, ..., n. The member will then indicate her opinion on the issue. Then we will calculate the smallest collection of abstentions that will avoid conflict.

The k-th element of the String[] voter contains the information about the k-th committee member -- the first element describes the member whose id is 1, the second describes the member whose id is 2, etc. Each element contains its member's opinion, either 'Y' or 'N', followed by the identifying number of each higher-numbered member who has formed an alliance with its member. Return a int[] containing, in ascending order, the identifying numbers of the minimal collection of members who must abstain from voting. If there is more than one minimal collection, return the one that is earliest lexicographically.

 

Definition

    
Class:VotingBloc
Method:abstainers
Parameters:String[]
Returns:int[]
Method signature:int[] abstainers(String[] voter)
(be sure your method is public)
    
 

Constraints

-voter will contain exactly n elements, where n is between 1 and 50, inclusive.
-Each element of voter will contain between 1 and 50 characters, inclusive.
-Each element of voter will be the character 'N' or 'Y' followed by a list of numbers.
-Each number on a list (which may be empty) will be preceded by one space (' ').
-The numbers on each list will be distinct, and will have no leading zeroes.
-Each number on each list will be less than or equal to n.
-Each number on the k-th list will be greater than the identifier of the k-th committee member.
 

Examples

0)
    
{"Y 2","N"}
Returns: {1 }
Here there are 2 members (1 and 2) and there is an alliance between them. Since they disagree on the issue, one of them must abstain. We choose 1 since it is earlier lexicographically.
1)
    
{"N 2","N 3","Y"}
Returns: {2 }
Member 2 has an alliance with both 1 and 3. If member 3 abstains there will be no conflict since all the remaining members vote N. If member 1 abstains a conflict will remain since 2 and 3 are allies who disagree. If member 2 abstains, 1 and 3 are no longer in conflict. So there are two minimal sets of abstainers, and {2} is earlier lexicographically.
2)
    
{"N 2 3 4","N 3 4","Y 4","Y"}
Returns: {1, 2 }
Each member is allied with all the other members. The only way to avoid conflict is for all those whose opinion is 'Y' to abstain, or for all those whose opinion is 'N' to abstain. Either way it will take 2 abstentions.
3)
    
{"N 2 3 4","N 3 4","Y 4","N"} 
Returns: {3 }
This is the same as the preceding case except that now 3 of the members agree on 'N', so it takes only 1 abstention to avoid conflict.
4)
    
{"Y 2 3 4","Y 3 4","Y 4","Y"}
Returns: { }
Everyone agrees, so no abstentions are needed.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AdaptiveRouting

Graph Theory, Simulation



Used in:

TCHS SRM 27

Used as:

Division I Level Three

Writer:

lovro

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7329

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10651&pm=7329

Problem Statement

    

A network consists of routers and links. Each link directly connects two routers. Links can transfer data in both directions, and have unlimited bandwidth but limited transfer speed. We know how many time units it takes for each link to transmit a packet from one end to the other.

The routers know the layout of the network and relay data packets so that the packet reaches its destination in the shortest possible time. Suppose a router wants to send a packet to some other router. The source router will calculate the shortest path to the destination router and send the packet to the first router on that path. That router will then proceed in the same way, and so on until the packet reaches its destination. If a router can send to more than one neighboring router and have the packet delivered in the same minimal time, it will send to the lowest-numbered of those routers.

When a link fails, the two routers it connected know about it immediately, but the other routers do not. The two routers generate control packets containing information about the failed link and distribute the control packets to all their immediate neighbors (over links that haven't failed themselves). When a router receives a control packet, it updates its internal layout of the network and passes copies of the control packet to its neighbors.

If a router receives more than one packet at the same time, it will analyze all the incoming packets before generating any outgoing traffic.

At time index 0, a number of links failed and a single data packet was sent from router A to router B. You are given the initial layout of the network as a String[], the list of failed links as a int[] and the integers A and B.

The routers are labelled with integers between 1 and 99. Links in layout will be formatted as "ROUTER1 ROUTER2 TIME", meaning that the link connects routers labelled ROUTER1 and ROUTER2 and it takes TIME time units for packets to be sent over it. A value of x in failed means that the link described by element x of layout has failed (index is 0-based).

Return an int, the number of time units needed for the data packet to reach router B. If the packet can never reach the destination, return -1.

 

Definition

    
Class:AdaptiveRouting
Method:deliveryTime
Parameters:String[], int[], int, int
Returns:int
Method signature:int deliveryTime(String[] layout, int[] failed, int A, int B)
(be sure your method is public)
    
 

Notes

-There can be more than one link connecting two routers.
 

Constraints

-layout will contain between 0 and 50 elements, inclusive.
-Each element of layout will be formatted as "ROUTER1 ROUTER2 TIME" (quotes for clarity).
-ROUTER1 and ROUTER2 in each element of layout will be distinct integers between 1 and 99, inclusive, without leading zeroes.
-TIME in each element of layout will be an integer between 1 and 10^7, inclusive, without leading zeroes.
-Each element of failed will be between 0 and n-1, inclusive, where n is the number of elements in layout.
-failed will not contain duplicate elements.
-A and B will be between 1 and 99, inclusive.
-A and B will be different.
 

Examples

0)
    
{ "1 2 1", "2 3 1", "2 5 1", "3 4 1", "4 6 1", "5 6 1" }
{ }
1
6
Returns: 3
With no failed links, the packet gets sent by the shortest route (1 -> 2 -> 5 -> 6).
1)
    
{ "1 2 1", "2 3 1", "2 5 1", "3 4 1", "4 6 1", "5 6 1" }
{ 5 }
1
6
Returns: 4
The link between routers 5 and 6 has failed. After 1 time unit, the data packet gets to router 2. At that same moment word of the failed link gets to router 2 from router 5, so router 2 sends the packet through routers 3 and 4.
2)
    
{ "1 2 1", "1 2 22" }
{ 0 }
1
2
Returns: 22
The primary link has failed so the packet is sent through the auxiliary (slow) link.
3)
    
{ "4 3 100", "2 4 3", "3 2 1", "2 5 1", "4 1 2", "5 4 1" }
{ 2, 5 }
1
3
Returns: 108
4)
    
{ "10 12 5", "10 11 2", "11 12 3" }
{ 2 }
10
12
Returns: 9
5)
    
{ "53 21 6", "53 21 4", "9 85 4", "9 90 7", "53 90 1",
  "21 9 7", "85 7 5", "90 47 7", "85 9 3", "53 85 5",
  "7 47 9", "53 7 9", "7 47 1", "21 47 6", "90 47 2" }
{ 14, 9, 7, 8, 0, 3 }
53
47
Returns: 12
6)
    
{ "65 37 24", "37 2 66", "65 37 32", "65 46 97",
  "65 3 52", "37 3 66", "65 77 50", "3 56 99",
  "77 3 100", "3 2 39", "46 3 75", "56 46 79",
  "46 2 83", "3 77 73", "3 2 60", "77 2 90" }
{ 10, 4, 0, 3, 8, 15, 12, 1, 13, 9, 7, 2 }
65
2
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MoreBlack

Graph Theory, Greedy, String Parsing



Used in:

Delta Round 3

Used as:

Division I Level Three

Writer:

andrewzta

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7308

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10721&pm=7308

Problem Statement

    

You are given a rectangular board containing m x n squares. Some squares on it are missing.

You must color the existing squares white or black, so that the number of black squares is maximized, and no two existing squares of the same color have a common side.

You are given the board as a String[] board, where the j-th character of the i-th element represents the square at row i, column j. Missing squares are denoted by '.' (dot) and existing squares are denoted by '#' (sharp). Return a String[] in the same format, where all '#' characters are replaced with lowercase 'w' for white squares and 'b' for black squares. If there are multiple solutions, return the one among them that comes first lexicographically. That is, you must minimize the first string, if there are still several solutions, minimize the second one, and so on.

 

Definition

    
Class:MoreBlack
Method:color
Parameters:String[]
Returns:String[]
Method signature:String[] color(String[] board)
(be sure your method is public)
    
 

Constraints

-board will contain between 1 and 50 elements, inclusive.
-Each element of board will contain between 1 and 50 characters, inclusive.
-All elements of board will contain the same number of characters.
-Each element of board will contain only '.' and '#' characters.
 

Examples

0)
    
{".#.", "###", ".#."}
Returns: {".b.", "bwb", ".b." }
1)
    
{"#.#.#.", ".#.#.#", "#.#.#.", ".#.#.#", "#.#.#.", ".#.#.#"}
Returns: {"b.b.b.", ".b.b.b", "b.b.b.", ".b.b.b", "b.b.b.", ".b.b.b" }
2)
    
{"######"}
Returns: {"bwbwbw" }
3)
    
{".#.", ".#.", "###", ".#."}
Returns: {".w.", ".b.", "bwb", ".b." }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Problem Statement

    The execution of your program in this problem will take place in two stages. In the first stage, you will be given a large undirected graph, and will have 30 seconds to perform any processing you desire. In the second stage, you will be queried about pairs of points in the graph, and must determine the distance between them. In the second stage, you will only be allowed 2 seconds of processing time, for 10000 pairs of points.



Scoring will be based on how how much time you use in the second stage, combined with the accuracy the distances you return. The accuracy will be computed using the root mean squared error (RMSE) of your returned distances. In other words, for each distance, we will compute the error from the correct distance, and square it. We then take the average of these squared errors, and finally take the square root of this average. We will then add time to this error, where time is your stage 2 execution time, measured in seconds. Your final score will be 10*tests minus the sum of your individual scores, where tests is the number of test cases. If you score over 10 on any test case, or you fail any test case (exceed time, crash, or provide an invalid return), it will be treated as if you scored 10.



Each graph except the examples will have one million nodes. The nodes will be numbered from 0 to 999,999. A value D will then be chosen between 5 and 20, along with a real value a between 0 and 1. For each node, D edges will be created. When creating an edge from node i, it will go to node j (where j does not equal i) with probability proportional to ((di,j)-a-(di,j+1)-a), where di,j is the minimum of |i-j| and N-|i-j|. This may generate duplicate edges, so there may end up being fewer than N*D edges in the graph given to you. Finally, the nodes will be randomly permuted so that the numbering used to generate the graph is lost.



You should write a method process that takes a String[], representing the graph. Element i of the input is a space delimited list of nodes that i is connected to. For conciseness, if j appears on i's list, i will not neccesarily appear on j's list (though it may), though the edges are undirected. The method query will take two int[]s, and should return a double[] of the same length. Element i of the returned double[] should contain the distance between u[i] and v[i].
 

Definition

    
Class:Distance
Method:process
Parameters:String[]
Returns:int
Method signature:int process(String[] g)
 
Method:query
Parameters:int[], int[]
Returns:double[]
Method signature:double[] query(int[] u, int[] v)
(be sure your methods are public)
    
 

Notes

-There will be a path in the graph between all queried pairs of nodes.
-While some of the examples are smaller graphs with fewer queries, all of the test cases will be on one million nodes, with 10,000 queries.
-While the actual path lengths are clearly integers, you may find it useful to predict fractional values. For example, if you are not sure whether the path length between two nodes is 8 or 9, you might predict 8.5.
-The memory limit is 1024M and the thread limit is 32 (including the primary thread).
-java.util.Random is used for all random number generation.
-There are 20 non-example test cases.
 

Examples

0)
    
"11 !\"\"\"#\"#\"\"\""
Returns: 
"This test case has 10 nodes.  D = 5 and a = 0.6294993817708533.  There are 10 queries."
Download

Each of the first N lines represents a single node. Each line starts with an integer K, and is followed by K other integers representing K edges. For example if line 0 were "2 83 76", it would indicate that there were edges from node 0 to nodes 83 and 76. Following these N lines, are a number of lines containing two integers -- the queries. All test case files are formatted the same way.



Note that the file format is slightly different from the input format. The graph in the file for this test cases is represented by
2 8 6
4 5 0 4 2
3 0 6 9
3 7 8 0
3 5 1 7
3 9 4 1
4 4 0 7 9
4 4 1 5 8
4 3 7 1 2
3 2 5 1
On the other hand, the String[] input is:
{"8 6",
 "5 0 4 2",
 "0 6 9",
 "7 8 0",
 "5 1 7",
 "9 4 1",
 "4 0 7 9",
 "4 1 5 8",
 "3 7 1 2",
 "2 5 1"}
1)
    
"12 ##\"################\"###\"#\"#\"\"#\"###$##########\"#$###\"#####\"##\"#######\"\"#$#\"\"#######$\"\"#\"##\"##$###\"\"#$"
Returns: 
"This test case has 100 nodes.  D = 20 and a = 0.4809864913712196.  There are 100 queries."
Download
2)
    
"13 $#$$$##$$##$$$$#$#$#$##$$##$$$$#$$####$$#$$#$###$$$#$###$$#$##$$#$#$$$$$#$$##$#$$#$#$$$#$###\"$\"#$##$#$$#\"$#####$###$#$$$$\"#$$$$$$$#$#\"#$#$##$#$$####$#$#$$$###$$$#\"##$##$$######$##$$#$$$$#####$#\"$#$#$$#$$$$$#$#\"$$#$#$$##$#$$$$#$$#$$#$#$#$#####$#$#$#####\"\"#$$$$\"#$!$$$$$$$###$$$#$$$$#$###$\"$#$$$##$#$$$$$$$##$###$$$##$#$##$$$####$$$\"\"#$$$##$#$##$$$$#$$$$$$$$##$$$$###$#$$#$#$##$$$#$###$#$$##$#$#\"#$$$#$#$#$#$$#$$$$\"#$$##$$##\"#$\"##$\"\"#$$##$####$$$#$#$$$##$###$#$##$$#$$$$$#$$#$#$$$##$$$###$##$$#$$$$#$##$\"$##$$$###$###$$$$$$$#$$#$$$$#$$#\"$$##$$$#$$##$$####$$###%##$#####$#$$###$##$###$$$$$$$$$$$$##$##$#\"$$#$####$$$#$#$##$$$#$#$#$$$#$$##$#$$$\"#$#$#$#$#####$$#$$#$$#$$##$#$##$##\"##$##$##$#$$$#$$##$$$#$####$$$$#$$$#$###$$#$#$##$#$##$$#$##$$$##$$##$$$$$$###$#$#$$#$$###$##$$#$#\"###$$##$$#$$$\"##$$$##$$$$$$$$#$$$$$#$$###$#\"$$$###$$$$$$$$#$\"###$$$###$$$$$$\"##$#$##$$$$$$#$$##$$#$$$$$#$\"#$#$$$$###$#$#$$$$$$$$$$$$$\"$$$#$###$##$$#$####$#$##$$$$$$$$#$#$$#$$#$$$#$$#$\"$#$$#$$#$$##$#$#$##$$$##$$$$$#$#$##$$$$$###"
Returns: 
"This test case has 1000 nodes.  D = 16 and a = 0.05128392223198952.  There are 1000 queries."
Download
3)
    
"14 &%&%&&&&%%%&$&%&%&%&%%&&&&%&&%%&%%&%%$&%%&$%%&&&&&%%%%&&&$%%%&%&%&&&&%%%$%%%&%%%&&%$%$&&&%%'&&$&%%&&&%&&%&&%%$$%%&%%%%%%&%&%%%%&&$&&&%$&$$&%&&%%%&%%&&%&%$'&%$%%%$&&$$%&&&&&%&%&%&$&&%&%&&&%&&&&&&&&$$%%%$%&%&%%&&%%&%&&&%&%'&%%&$&&&&%%%\"%&%&#%%%%&&%%%%&%'$&%&%&&%'%&%%%&%%%&&$&%&%%%&%%#%%#&$&&%%&&&%&%%&%&%%%&&%%&&$&%&%&%&&'&%&$&%%$&#$$&%$%&&&$%&&%%$&%%&&&$%&&%%%%&$$%&%&&&%%&%%$%&&&&%%&%%$%%%&$&%%&&%%%&%%&%&%$&&&$#$&%&%&%%%&&%%%$%%&&%&%$&%&$'&%&&&%%&%&&%&&'%&&%&&&&%%%&&&%%#&%%&#%$&&&%%%%&%$%&&&&%'%&%&%%&%%%$%&&&&&%$%%&&%%&&&%&%&&%&&%%%&%%%%%%&%$&%%%%&$$%%%&%%&&&&$&%%'%$&&%$&&%%&&&&%&&$%&%&$&&&%&$&&&&&%&&&%#%%&&&&%%$%&%%%$%#%$%%%&&%%$%&%$&%&&&&%$&&%%&&'%&&&&%&%&&%%&%%$%&%%&&%%#&%&%&&&%%%'$$&%&%%%%&$%%%%&%&%&&$&%%&#%$&%&&#&$%&%%%&&&%&&%&&&&%&&&%%&&&&$&&%%&&&&%%&&&%&%&%&%%%%%&%&%%&&&&%%%$&&%&%%%&%$%&&%%&&%&&%%&%%%&#%&&'%%&&%&&#%&%%%%%&$%&&%$%%&$&%%&&%&%%%$&%%%%%%%&$&&&%&$'$$%%%%%&%&%$&%&&'%%&&&&&%&&%&%&&&#%&%%%&%&%%&&'%&$&&&&%$%$$&%&%$%$%\"$%&%&%&%&%%%%$%%&%%&%&%%%&$%&$&&%&%&$%&&&%%&&&&&&&%$&%%&&&&&&%&&%%#%%%&%%&%%'$&&&&$%%%\"&%%&#$%&'$%%&&%%&%%$%%%%%%&$&&&%&%%&%%%&&&%$&%&#&#%%%$&%&&%&&%&%$$%$&&%&&#&&%&&$&&&%&&&%&%%%&&&%%&&%&$&&#&&$%&%%%%%%%$%%$'$%%&%$&%%%%&&%$&&&&&$%&%'%$%&&&%&'%&&&&&%%&$&%&%&%%&&%&%&%%%%&%%&&%$&%%$%&#&&%&%%&%%&&%%%%%&&&&%%%$%&&&%&%%%%$%%%%$%%&%%&&%%%&&&%%%%$%&%$%$%&&&%%%%&%%%%&%%&$%$%%&&&%&&&$%&&%&&&%'$&&%%&%&&%&%&%&%$&$&&%&&%%&%&%$%$$%&&%%&&%&$%%%%%%%&&&%&&&%%%%%&%%&&$$%&&&&%&$%%&&#&&&%%&%&&&$%%%%%$%&%&%&$$#&&&%&%%&%$%%&%%%&$$$$\"%&&&&$%&%'&$%&$%%%%&%%&%%#&&&$&&&%%%%&&&%&$%&%%&%'%&$&&&&%&&&&%&&'%&%$%&%%%$&&$%%&%%$&&%%%%$&%$&$%%&'%%&$&&&%&&$%%&&&%&$%&&'\"&%&&&%%%%&%%%%%&%&%&%$&&%%&&%%$&$$%%&$&&%&%%$&&&%%&%%%&%&&%$%%%&&%%&&'%&%&$$%%%%&$&%&%#%&$&%%%%%$&&%%&%%#%&%&&&%%%%&%%'%$%&$%%%&&&%$&$&%&%%$%%&&&%&&%&$&&%#%%%%$%%$#%%%%&&%%&&&&&%$&&%%%$&%&%%&%&%&#%#%%&&&&$&&%$&%$%%&%&%&$&%&%%%&%%&%%&&&%%%%%&&&$$%&$%&$&$&%#%#%&$%&%&$%%%&&&%%&$%&%%$&&&%%&&&%&&&&&$$&$&%%%&&%%&&$%%&%%%%%&%&&&$$&%&%%$&%&&%%'&&&%'%%$&$%%&%%%&%%$%%&%%%&%$&%%%%%%%&%'&&&%%&%%%%$&\"%%%%%&%%%&&%%&%%&%&%&%&%%&&%%$%%$%$&&$%'%&&%%&%%%%%%%%%&%&%%&&$&$&$$$&%$&&&$&&&$&&%%&%$%%%$%%%%&%&%&%%%&$&%'%&'%&%$%&&%%&%%%%$%$%%%%%%&&$$%&$%%&%$&%%&%$&&%&'&&$%%&&&&&$&%&&&&$$%&&&%%%&%%%&%&%&%&&&&%%$%#%$&&$&$%&%&&%&&%%&%%&$$%&%&%%&'%%&%&&&&$%%%%&&&$%&%&&%&&%%%%&&&%'%&%%&%%&$%$%&%&%&%$%%&&&%%%&%%%%%$%&%&%&'%'$%&%&&$%&&&%&%&&&&%&$&&%&%$&%'&&%%$&%&%%&%&&%&$%&&&&&%%&%&&%&&$&%&%'&&%%&&$%&%%$&%%$%%%&%%%&%&&&%$&$&&%%&&&&&&\"&&%%%&&%%%&&%&%%&&%%&%$&%&&&%%%%%%%&&&&&#%&%%&%&&&&$%&%&&&'%%&%%&$$%&&&%%&%%%%&%%$&%%&&$'$$&%&%%&&&&&%$'&%%%%%%%#&%%&%'&%&&%%%%&%%%&%&$%%$&&&#%&&%&%%%&%%%&&%&$%&&&&&#&&%&'%%$$&%%$%&&&&%%%&&&&&&%&&%%&&#%&&%&%$&&&#&%%$&$%%%%%$&&&%&%&&&$%$%&'&%%&%&&%&&'%&%&%&%%$&%%&&&%%%&%%&&&&&%%%&&%%%#&&$&&&%%&$&&&&&%&%&%&%&&&%%&%$%&&&$$%&&%$&&%%$&%%%$$&&%&&#&&&&$$%%%%#%%%&&%&&'&&%%%$&$%%%&&%%&%&&&$&%&%%&%%%&$$%$&%&$&%&%&%%&&&$%&'&%%&%%%%&%&&&&&&%&%&%&%&&&&%%%&&&&&&&&%&&&%$%&$%&%%%%&'%%$%&&&%%%&&&&%&%%$&%&&%&%$%%%%$$%&&$%$%$%%$&%%%&%%&&&%$&%$%#%&%&&%&$&%%%%%#%$&%%%#%%%&&&%%$%&&%&%&&&&&%&%%%%%%&&&%&&%&&&%$&#%&&%%&&&%&$&%&&%&'%$%%&&&%'&%&$%%%%&&$%$%$&&&&%$$\"&&%$&&&$%%$$%%%%%%&%&&&%%&%%$$&$$&%%%%%&$%%&&'$%%&%$%&$%&%&&$%&%%&%%#%&&#&$$$&&%$$%&$%%%$&&%%&%&&&&&#%$%%%&%%%%$%%&&&%%&%%%&&&&&%%&&&&&%%%%$$%$%%&&&$&%&#%&$&$#&\"&%&%%&%&&&&&%&%&%%&&#&&%&$&&&&&%%&%&%&'%&&&&$#&$%&&%%&%#&&&&&%&%%&%%$&%&%&&%&%&$&&%%&%%%&%&%%&&&&%%&&%%%%&%&$&&$&&%&$%%&&&&&%&&&&%&$&&%&&\"#&&%#&%%$%&&&%%%%$%&%%&&%%&&$%&&&%&%&&&$%&%%%%&&%&%&%$%$%&$%%&%%%&&%%%&%&%$&&&$$%&&&&%%&%%&&&%%&$%%&&%&&$%%%&%&$&%&%$$$%%%&$%$&%%&$%&&%&&%%&&&%&&&&&&%%%&&&%&&&&%%%&&%%&%%&'%%&%$&&%%%&'%&%%&&$$$&%%%&&&%&&%%&%&%&&&$%%&&&%%%$&%$%&%&%&%%&&&%&%$'%&&&%&#%'%%&%%%&&%%&%%&%&%$$&%$&&%&%&%%&&&%$%&%%$&$&%%$&%$%&%%%'%&&%%&%&&&&'%%&$$%%%&&%&%%&&%%&%%%&%&$&&%&&%%&%%%%&&&$%&%%&&%&&$%%&&%&%%&&&&%&&%$&%&$$#&%%&%&&%&%%%&%%%&%$%%&%%&&%%%%%&%%&%%%&%&%%&%%%%%&&&$%%%%&%&%&%%&&&&%%%%%'&%%%&&$%&%%%%&%%&&&&&$%&&&&&%&%&%&&$&&&&$&&&$%&&#%%%&%&&&&%%$%%&%%%$&'%&&%%%%&%#%'%&&%&&%&&&#%&&$&%$&&&$&&%#$'&&%&%%%%&&%$%&&&%&&&%$&%$&&%&&&&%%%&&&%&$&%%&%$%&&$%%%&%$%%%%&&%%&&#%&&&%&#%&&%%&&&%&%%&&$%%%&%&&&%&%%%$&&$%%%%&%&%%%%&$%&&&&$%&%&#%%%&%#&&&%&&&&$%$%%%&&&%&&$%$%%%%%&&%&%$%$%&$%%%$&%%%%%%#&&%%%%&&$%&%$&$%&#$%%%%%&&&&%%%$%&&%%%%%$$&&&&&#&&&&%&$&$&%%$%&%&&%&%%%%&%&%$$%$%&&&$%%%&%&&%%&%%$&%$&%$#$&%%&&%$%&%&%$#%%%%&%%%&%&%%%%&&&%$&%&%%&&'%%&$$&&&%$&%&%&&&&%%$%$&$&%$&%%%%%$&&&&&%%%%%&&%%&$&$%$%&%&%$&&&$%&%$%&$&&&&&%%%$&&#%'%%%$%%%&&&%%&&%&$&&&%%&%%%%&%&%%%&&&&%&&%%%%%%&%%&&&$%%&%$%%$%%&&&&&%&&%&$&$%$%&&&%&%&%&%&&&$$%%&&$%&&&$&%$&%%$%%&%%&%%&%&$%&%%%&&%&$%&&%%%%%%&&$&&&&%%%%&&&&&&&&$%%&&&%&&%%&%%%%%$&&&$&&&%$\"&'%&%&%%$%&&%&%$%$%&%%&%%%%%%$&%&&&%%%%&&&&$%&&%%%%&$%&&&%%&%%%$%%&&&%%%'%$%$&%%%&&&&%%&%&%&%%$&%%%$%&&$&&&&%$&%%$%%&&$%&&%%%%%&%&%%%%&&%&$%&%'%%&&&&%&$&&&%&&#&&%&%&'%&&$&$&&&%&%%%&$&%&&%#&%%%&&%&%%&#&&&&&%%&&#%&%%&'%&&&%&%%%&&&'%%&%%&&%&$%&%$%&&%&&$&%&&%&&&%%%%%%&%&%&%&$$%&&$%%&&%%&#&&%$%&&&%&&%%%%%%&&%%&&%&&&&%%%%&&&%&%&%%&%%%&&&&&%'&%&%$&&%&&%%&%&%%%#%%&&&%&%%&$'%%&%%$&&$&&&%&$&%&&%$%%&&&&&$%%%&#&&%$%&%%%%%%%%$&&&%&%&&%$%&%$%&%&%%%$&%%&$$%%%&%&%%&&%&&%$&%%%%%'$&&%$&&%&&%%$#$&%$&$%%%&%&&'&%&%&%%&$%&%%&%$%$&&%&%%%&%$'&&%%%%%&&%%%&&&&%%%&&%&%'$$&&&%%&%%%&&&%%%$$&&&&%%$&&%%&&%&%%&$%$'%$&&%&&%%%&'&&%%&&&%&%%&%%&%&&%$%%%&%%&$$&%%&$&&&%&%&%&%%%%%&&%&%$&%&$&&&&$&&&%\"%%&&%$%%%$&&%'%\"&$%%&$%&&%&&%&&&$&%%&%&&%%%&&$%&%&&&%$%%&&$%&&&%%$$&&#%&$%$&&&&&%%%&%%$&&%&%&%&&%&%&&&%%%%&%%&&&&&&&%&&$%&%&%&&&&%%&%%&%%%$%%%$&&&$$&$%$%$&%&$%%%%$$$%%&&%%&&$%&%&&'%$&&&&&%&&'%%&%&&&&&&&%%&%&&%%&$%&%&&&&&&%%%%%&%&&%&%%%&%&%%&%%%&%%%%$&&'$\"%%%&&&$%'%%%'%%&&%%%%&&&%%%&&&%&#&%&%%%%&&'$%%%&&'%&%%&&%&&%$%%%%%%%&%%%%$$&&%%%%&%\"%%%$&%&&%$$&$%%&&&%%%&&%%%%&%$&%$&%%&%&%&&&%&%&&&%$&&%%&&&&%%%$%&%%%$%%%&%&&&&&&&$$%$%&%&&%&&%%%$#%%%&%%&&%%%%%%&&&&%&%%%&%&%&%%&$&%&$%%$$$&&%$&&%&%&%%&$$%%%&%%&&%%%&%%&&'%%&%&%&%&&&&%&&&%&&$$&&$&%%&%#&$$%%&&&%%%%$$$%&&%&&%'&%%&&&&%&&#&%%%&%%&%&#$&&%&%&$%&%$&&%$%%&&%%%%&&&&$%%&&&&%&%&%%%%&%'%%&#&%%&&&&%&&%%%%%%%%%%%&%&&&%&%%%&%&%&&%%%$&%%&%%&&%&&%%&%&%$$&&%&$&&&&$%&%&%%$%&&&&%&%&&&%%%#$#&&%&&%%&&$&&&$$&&$%&%%&&%&%&&%&$$&%&$&%&%&&&%&%%%%&%#%%%%%%$%&&&%&&%&&%$&&%&&%&%%&%%%&%%&$&%%%&%&%%%%%%%&&%%%%&%&&&$%&&%$$%&&$&$&&%&&%&$%&%$&%&&%&%%%%%&&%$&&%%$&%'%&%%&%$&$&&%&&&$&%%&&&&&%%&%%%$%$&&&%%%&%&&&$&%%$&%$$&&&!&%&&&%%&&%%&%&%%&#&%&%%%%%%%%$&%&&%%%$&'%&%&%&%%&&&&%%&%&&&%&&%%%%#%&$&&%$%$%&&%%%%&%$%$%&$%\"&%$$&&'%&$%&&$&&$%&%%%$%%''%%&%&%&%&&%%%$&%&%%%&&&%%&%&%&%%&&&&%%&&%&%&$$$&%&%&%&%&&%&$%&&&%&%&$%&%#%%%$&%&%&%$%&&&$%%#&&&&&$$%$%&&&&%&%'&&%%&%%%&%&%&%&&&&&&%%%&%&%%&$&&&&&&%%$&%#'&&%&&&%%&&%%%%%%&$%%%&&%%%%%&&&%%%&&&%%&%%%&%%%%&&%&&%$%%'%&&&#$#%$%&$%$%&$$%%&$&&%&&$&%$%%&%&$&%%&&%&$%%%&%&%$%&%%&%$&&%&&%%%'&&&'&%%%%%&'%%%&&%&$%&&&$&%%%&$%%&&%%%%&%&$&&&%%&%$%&&$%&&&%%%$&%%%%#&&#&%$&&'&%$$$%%%&%&&$&%&&&&%$&&&%&&&$%&$%&&&&%%%$&$%&%%&&%%%$%%&&$#%%&%%%%%%&&&&%%%$&&%%%%%$%&&&&%%%&%$%&&$%$%%%&&%&&&%%&%&$$&%%%&'&$%$&%&&%%&%&&&%%&%%%&&$%&&&$%&$%%%%&%$%%%&%%%%&&%%&%$%&'%&%%&%&%&%%&%%&%&%%&&%%&&%&&&%%&&&%$%%&%%%%%&%&&&&&$%%$%%&$$$&$&$%%&%#&&&&$%%%&%%&$%&&&&&&&%#&%&&&$$$$%&$%&&$%&&%%%%%&%&%%%%&&%&$%#%'%#%&&%%&$%%&%%'%%&&&\"&%%%&&%&&$$&%%%&&&%&$%&%#&&%&%&%&%$&$%&&&&%$%%%&$%'$%%%%%&$%&&&&&$%%&&&%#&&%%%&&%%&&%'%%&&$%&&&%&&&&$%%%%%&&$&$&%$%&&%&%&&%$%%%\"&&&&%%&$$'&&&&%%'%&%%%&&$$&%&&&&%%&%\"\"$%&&&&%&%&%$%%%&&%%%%%%%&$$'&%%%&$$&&&%%&%&%%&&&&&%%%%$$$&&%%&&%&&&%&%&'&%%&&%%%%&$$&%%&%%%%%&%%&&&&&%&&&%&&&&$&%$%&&&%%%%%%%%#%&%&&&&&%%&&&&$%%&%&$%&&&%%&%%%%%%&%&$%&%&%$%$%&$%&&%&&$&&$&%&%#%%%&$&%%&&%%%$&%%&%&&&&%$%%&&%&&&%%%&%&&&\"&%&#&%'&&&%&%&&%&&&%&&$%%&%%%%%&&&&&&&%$%%&%&%%%$&$&&&$&$%&&&%&%$#%&&%%%$%%%&%&%$&%%&&%&&&&&%&&%%%%'%%&&%&%&&&&%%$&%$&%%&#&%&&&%&&%%%%&&%%&&&%%%%&&&&%&%&%%'#$%%$%%&$%%%&%%%%'%%%&%%%$%&&%&%&%%$%&&%&&&&%&%%%&&%&%%$%&%%&%&&$%%%%&%#%&$&&&&$&&#&$&%&&&&&&&&&%&%%&&$&%&&%&%$%&&%&%&%&&&&&%&&$%&&$%&$%&$%&$&%%&&&%&&%%&&%%%%&&&&&%&&$%$%&%&&%&#%%&%%&%&&%$%%%$&&&&%%%$%$&%%%&$&%&&%&$%&$&&&&%$%&$%%%%%&%%%%$%&%&%&&&&%&%%$%%%#%%&&%%%%&$%%%&&$&&&%$%&%%%%$&&%%&'%%&&&&%&&&%&%%$&%&%%$%'&$%%&&&'&$$&&&%$&%$%&%&&$%%&%&&%&$&%%$%%'&&%&&&&&#&&&%&&%&&%$&%%%%%&%&%&&$&&%%%%&&%%&%&&&%&%&&%%%&&%&&&&$&&&&%%&%&&$%&$%&%%'%&&$&%%&%&%%%$%%&&%'%&&%&&%&&%&&&%&&%%&%%%%&%%$&&&$%%&%&&%%&&%&&&%%%%%&%&&#%&&%%%$&&%%&&&#%%%&%%%%&$$&&$%&&$&&&$%&%%%%$&$&&&%'%%'$&$&%$&&%%%$&&%#%%&%&%$&$%&%'%%&&&%%&%#&$%&&&&%&%%%$%%&%&%&$&&%%%&&%$%%%&&&&%&&&%&&%&&%%&%%&%%%&&&$&&%%$&&&&&%%%%&&%%$&&%&%%&%&&%%%%%$%%%&&%&&&%%%$$$&%&&$&%%%%&&&$$%'&&%$&%%%&&&%&%%&&$%&&'&$%#&&&$'&%&%&$&&&&$&&%%&%%&&%&&$%$&%%&&&%%%&$&$%&&%$&%%&%%%%&%$&%%$%&&&$%$%&&%$%%%&%&%%&%$%&%%%&&&%&&&%&&$#&%#&&%$%%%%'%%%&%%%&&&&%&&%%&%%&&&%&&&$$$$&$&$%$%%&&&%&%&&&%&%&%&%&&%&$&%$%$&%&%&%$%&%$%%%&&&&%%$%&$%%&%&#$%%#%%%%&#&%&%%&$%&&%&%&%$$%%&%$&%&&%%%%%&$%%%&#%%&%&%%%'$%%$%&%&%$&&&%%&%&&%&%#&$%%%&&&&%#&$%&%%$%%%%#%%&$%&%&&%&%$%%&&$%&&%%%&%&&&&#&$$&%&%%%&%$%%%&&%&%%$&&&&%$&&%%#$&&%&&&$&&&&%&%%%&%&$%%%%&%$%$%%$&%&&&%&&$&&'&&&&&$&&%#%&&&$&%&&%&%#%&%&$&&%%%%&%%&%$%%$$%&$&#%&%$%&%&&%$%&''$&'&%&$%&%&%%%%%%&%&&%&&&%&&%%&%&%$%%%%%&&%&%&&&&#%$%&%%%%%%%&&%#%&&&$&%%%&%&%%%&&%&&$%%&$%&&&$&%&%%%%%$%%$&%%%$&&%&$%&%&&%%$&&%%$&&$&&&&&'&%&%%&%%%$%$&&%&%%&%&%&%&$%&%&%%%%%$%&%&&&&&%%%%%%%%%&%%%&&$&%&&$%&%&%&&&&%%&&%&&&&&%&&$&&&&&%&&%%#&&%%&%&&%%$$'&%%%&&&&&%&%&%%%%&&'%%%%&&&'&%&&&&&'&&%&%&&&&%&%%$$$&&#%&&&%&$&%%$%%&%%$%%'$&&&%&%$&&&%%%%&%&&%%&%%%&%%&&$%&&%$&%&%'%&%&&%&&%&&&%&&%%%%&%&&&%&&&%&%#%&&%&%%&%%%&%%&&%%%%$%&%$&&&&$%$&&&#%%%%&#&%%%%#&%%%%%&%%$%%&%%%&%%&%&%#&&&%&%%$&&&%%&%%&%&&%%#&&&&&%$%%&$&%&&%$%&%&$%$$%&&&%&$%%&&%&&%$%&&&$%&%%&&%%&%'$%&%%&%&%&$%%%%$%&%%$$&&%%&%%$%$&%%%%$%%&$&&%%&$%&$%%&%&%'$&&%%%%$&&%&%&#$&%&&&&$&$&%%%%&$%%&&%&&%%%&&%%%&&%%%&&%%&%&%&$%&$&&&%%!#%&$&%%%%%&#%%&&%&&%%%&&%&&%&#$%&&%&%&%%%&%&%&$&%&%%&&%&&%%&%$%#%&%%%%&%&&%$$%%%'%&%&&%$$&%&%#&%%%&&%&%#&%%&&&&&%%&&&&%&%&$&&%%&%%&&&&%'&%&$&&&&%&#%%$&%$%$&%&%%$$&&%%&%%%$%%%&$&&%&%&&#%&&%%&&$%%&%&&&&&&&$&&%$%$%&&&%&&&%&&%&&%&&&&&%%%&&$#&%$&&&&%%$%&&%&&%$$%%&&&&%%#&$%%%$%&&%&%%%&%$$&%&%&&&%&&&%$&$$%&&&%%%$%%%%%&&&%$%%&%%&%&%%%%%%%&%&%&&&&&&&%%$&%%%&&&&%%%%$%&&$&%&&%&%%%&%%&&&%%$&&%%%%$%%&%%&&%%%&%%&%%%%%$&%&&&%&$$%%&&&&&&&&%%&%%&$%&%&%'$$%%%&$$%&%$&&%%&&%%&%$&%&%&&%%%&%&%%%&'%&$&&&%$&&%&%&&&&$&%&$%&%$&&&%%%'%$&&%%%%&%%&&$%%&%&&&%&&&&%&&%&%&%&%&&&&$&&&&"
Returns: 
"This test case has 10000 nodes.  D = 10 and a = 0.3403916445508408.  There are 10000 queries."
Download
4)
    
"15 6035,63/5+-25211*371/153.0506-654,4-71/0.2'1-2/1/734011./-*125335-01*424520+2-36503.1/1-6-00/4/3.6.(4+241457044+-+7/1.-01/2266/.0056234.(1.7.33.///0--0+2.2627/4.26+/0/*)1,-5027/203.+11/5..114251,*2-/6545'+63-74,1/34205.,0/02045//7-/*33613+.0&12-5+.--2.43)6+25034311.2.0.&.5-/2,862)/2344-3030233/065/363114656143/-/.23+52-53/4-3+02,10.2615.304-/3.6042613205424752145/84.+5*/4,/333'502(1+12230-7(.,64,.33..222/213)4-343(+8146340.0413/62/31,6/5(41)31/.201-3/66.-1+40,/,70533024844342.2/-3-132.+1&005533-53//3540.5560)/151.51/5-/+0*253.454/\"3/11430437137/041303/3/**06*+42,/0,3131*2.06+143*50/0/3.56211505&7/2*32)4/-0+-7620(-,)40/465*.500064641.5,4545064/4/.-/6-/4//6/62''8.053,51,52./2&,02+330/1/11.1106251,/23(-,0075.22(46+3344/710/6)2,3))+4.41+./4,3,/0240.,0)444591/003*0047,346..5-24027224/,020203.03-+0043216.,4213444.263551*0*-/&.23.3030/-13353-2346414054210112/01+0+1155-+1.85-1,0*131.421234*56012.014635152031.1*650.-3/433/54-320035.223-5.3032615104121.3101/236.01/-035524706/624,0/14024001713/022,/3/2.40/5.005//.115,/33.4/13,.533142-3.-0/+/3253'+5141/,,14234001.,0/67110202-+*4/.4+5-21/4,630036.470551354+0//-1,.5103004/2**6.11/6/341+4.07-,103512,8611./5-64363)2/26363-1*,531..3/0402//0/*6*-12511111'4/01152552.604,5.45..3457744/3336152,5.14535*213631+0'031210+25-344.81,1-4143222,543.2./44/07../07-12+.13/-,0.02)603+0/0.36/3104633//)-3,2/35/0224453270031003/0*+0,2/9*401/1/160/425635),4./2.12*7531,1604).24+1+46*3402+-31-05/1/521020/5.,-004115-4242.-/-0-3/13/33*14201)3..223,67.-)053314+32/023,-33*+.45433,7+*+.4122,&3431151/3-23125+24/(2+12*0213/7*'69/.5353562140,2//12-*+2203-5--./5262/40.65260-214454+/3(3141.2.5,3,.32/,00232+0023/401/136734,-0862244*(94/.)677)600*13133,32.2327.43002&-/'051421.4-224/0003/432*4125+/.02133.5/51--720612664334//-/1.81)44443301,3-2-3+3/5*0-4413751-+5:0371/8172+11,345,4.0104/0003/.+,)-/356))1(07502/.32,6(062,421..4-52,0+0-.522/4/721.3*336,*,346334*74921523,500124303-4573++,22070'76.1+,-/352456230134,313445663444)532.,3//+163+4433,00.6602/230140/5355.,.*.//3755,/371+-&6-6206/3/3,5.4)3,0103/05731114517+51*/17/33-01226,131141).(21-5).1130))1*16--+4.4320)2045+/./20,.1.1).,64022320,401/-3173*.446741+15-1030224.1'/0442446432-3+*10/644613/6-11/07/05/40340(4-/47.0/444/138062-3136/6+3..(0+34303302/0--2252663*.102+15402/*0)83-7.+043,'-432//*3,52,16%.22,,0+35/5.+4.1201.-'5602110)31,23+.0'*1*+2,)6490551+560/2675/25510.2,07.872234-637:.-.0/)0.-10/00602.-0-54581,4*41415-+52.0+)034//22060-41,0,546.1,075-3--.2/-0,/052,//.*/3-1303540463,1/+.563)3,50/2123516021)4.133*20+50,5391/07604625*01.13-+.0,5022.,5454,4//0,73/11634120..13,/2/75.0424.3,31220,2401*.,/57.663)02/2,*023/6105-01232///125+3/.22,2310,,5,85/*38744420(+*31/1255-1$(4+03-*0+3132295)14121)3-11-52.1144*4743,4).)4/5512667141/-(.,32/.01-00/21-200216(/562/.3/).05/555,.200/,/.6/2.20532.-3.061647/,+26.,,4./184*.1100/00517'124.3,044414,02-00,6.2360-3'/6-5-/22+)4.3410200771*.322343(32,1,25--94$.2/*02..105341+602-9.23)101/40/14-+3/5322(+02*21+/--,4.4.20314.4,2,5016/21,0*3750-2311-5+0,3+00-)3441/22/-2201.-+405.*0743421114-3/*45/1-,7/0231556,688/3016,-3252%-/500*06.4314/636512.0332(-)53-/21123-3/2.47544/312524../638/332.50535),40%0.(1/+.52/74/513,,312.-4140.2/01,252-(230453.2.3*+250/0.3-1)166-1323*31,10041',253.58(/3)12,.33.1'*7)1+215.61501140512.5.3/03.5/0421/4.6.1,*4*4/04/0724-5-)43/02/640-1+2,1/0+4//0/31.21252.+.00012//+12.1/31511.1.-123531///(1/13-630-07202-414443.65//*+76427+-.77/2441156,06735670/6'0242)24713-5(.110140(+/51+0+,4/6,//-./42037125-83/335**413.0-111442131051401452/244,62)0*2*.4+33+1+.40154/.3253/4143/.,..20.51/.25+-2-.2,/2/54.43/05//43,6-38061.214501*074143.352./0330)161/3)8,0612515-0,0153-41/)//212446.+.0,21.33/-10(1/3/14433+51462,-1/40.07/60/2/4)2)..06444.2.305/,262#2+1-026205/134..443*6.21133+1,3512*5+443/2,-.331)-0020,+4*-36)34116001741/0/3621&)/4'.&10/03,'003.,3+,-/-3002,32,/+5/1)/5-6/50-86441.1-714(/7-2321373332.4,0101-132003303/).2.521*351-),#--7,,,64,44+-14'3-.0.5,/5*1.211,+-16/)14330626.86/5.0,1'.365.53050+411./(1./63343,,9413-.029//61332021202&002,2034.(*)2405+)2,012237.2)-5*04%1%537-4302204+2222-0067008061423,0,/41./2751.-23330121433/1215/,.3-4-/1/2540&1/5)341+3/314)(5'40,00.0(020,831,-2241341.4060,262.4/(.0220.111.5+021**07,2,73.406-35+)1.114+/27*/2531&420//45.4.++/.222-,1205.*3401071272411/41+44*,+4-.72-053362434/162(231501.0)415255,2166222401/3.+00421.3/-33-/2333,/3-23/3121+.25/3*-5.3.+143772424)/3510350512-5014+2.1607383,314+(.,363.3-1,312-16-4.20).1.-20)/340060&121232,51*40.,(*153-,/72/250,1104262242//4.32/514../3/,234/.7-/4170416010903-1422/544.62,/8&12.5//-15+0-,323103/3,//223362/.,10.22130726417)142/2343--0423-054/304/1601/0+22301-1/+2162.-)32.1105/3411,4314252201)726/2..0-05*2534'136,3010.,-/63*6.52.32127-123655-13,1430('3100+'.1*5/30)'2'+/35211/,3024/,,11(0-25235353,'0244122,7.1//132544514.463430/.,2.48+3--301-46-,/51/*05400/...-/23,+147,52.,160+21-)(,+331.0/41)/33251703//35.24,*3.4-'25716(+.60.(323201,/0233,//0+55.(26/04.+10.2+3+13252.3.4+66/3043,2,212.4+576./1&/5+044261,(2/41-1/13+./3400304/.63426022354,//3.-)-63/*2.412025*15116-6224-56141./3(.53530)165)1173+.4&3261824344013.1,17.14531011/1,52010./*2/00//-.4164361)6401234.41.016312233*5144162,72/56622/40//37.3/..+/)141-110(2)130/+512.011262,,44314*21183241+3035,+5/*9*31.*0/152311223-62330)3,31/134237110.*13+106/5320*/1432-24225-*0./363.3.2./+12336/323122/.7+).1,/5//0510,//1602.4-/20+-30//0,(3-61-15470,03.206.1'/22*337*5/4,3*200/417362.2/24521,405421%/050,%1.66/,3462353-37341,/4421420,3120-1$--0/0*/3352.206)50702160+6-211083335/42)02,4421324-32.313*22//3+1/.02-2*10(/210)3650.302.0/00/.1131/.6+21-,-2803+0055212%/611444+/)-3,3/4443405//-20,35.363-720333562/1-.46154103/./+52,5/(41*40(2/3./3,$3512*5./+,21/1105100.500/6064+.*/3/41/.52332242.4-000.581314,325316//.2426*243-931414363074+8*225&*.01670-721(.00002,2041.,315.46)23131)045360/-33+41+(,5-81/0/2/22,.65.535102,50+4//6,1142)1,23438.321513/065305.+3160622311435/50(355/0(1.5-331020,/1*051/2.5330'.3+1+153..6084152*.54863420/33//2/2413000613*14,05425526/4/5745+3431203)504,5,2131/4545-52/2*06-*343-4+66+033583(2,+75+,6',2+143(/+012'211)3.-003126436+423/,/144+2*1)3-71-4/-742034-.2+5-5/22607-3-23122/2(//23.4)71.6-)056+/0'546/0/.3622.+.42400/353.21,2511(.02,0+/+01.001/-2342/.-.,31,(13$-03432513422-2-'4060023015*3*3*5.0443-3--2)11,5.+32052720350081/(2.60.2$245-16103(/02*151253-+2+315//0406-722*+*.4..3441032.244-252-4-.116/4.,2/66523-2-4104635-..,7454.*,2405.1-+072261/30+/5+21-*0600//234.4.*,)1050/13+2//2.423/41*/,/4231/4/3)4314/-25+553(.,-34-7442604)31652.08)23*--184..-.33)(/-5*+*.3-3711236003/42614023132022(5.,1*402441645/508354..('23-.1//2.4*,14/$+50.1.61'044/0,5243/03.,2-2,0424..8-03166,/3-/,5,.5-2/63//-.53&3-/034.421--*.5.440+17&022524/0565145.15/3(**10/052,3246705215--,61)446(/5,03+13002/805242/./(33,537**--014/&/1-113-/23215)/.21423-0-30.2432,3,5+4,,,546-3630'8)1740(-026240-)3.7.1...10/733053,).1.1+1-+/362+333+50*/4*/4224/450/324/632044020/7223/+2/04//.2,-30-/40,2313.24*3/3332-+2.,1-26.63313.1313&4347)3/34063-//20./3-1/7-5.0143/624265137-6'2-263/3432,03//5335103+03.462,27.064-,72520)$02326314.1*2(3+.8..21/136410415,/30312-+03)1/12244,06)110-262,-/0/,+0664/.51.41213150220441.4(+5231*2/14(72.53466.146*/442424/2-+836102453+/42.+4(1,3453.13/0545(4/4-21,1,--1)/2111.61/4625)3653+,//.-06/3310063413130110/*,47-3-.5435113-052-.1/1*3617/37-'2,*,3454.-3--133623041-,34--+.4420..$5-1+355,.244.412,2544+121,2/423+,5.+,5/1630-12242.351-52,-.,13-///-436420--/15/.650546/5/3/31425.146.13,762*,,413+1/*/,,5,1/643-3150241/)1150927.12-43.//./-23..6*04/.0114-6225.613-1///41221252)'26-504350+,5//1713/.61137323359234461,2240.51-1/.05+22108(24512'26.673543-2.022.7'5*5610-.44/110'0/)2/350045-553.04/5-4+3131-0.2/6,0211-/,63015-0/43454420/5/--63*55,232)-31324,03*.31').-30.0,3+1*-6432063324122804/1-4.2424/47613/.-*461041284/4.11(20424543.5-7(54-3/+03.1,.10123454/*0162.,51-2.,6,-3.,/074703056442.3607..43104622*851.0/1+82-6521371143-//31-14/02644/63/0/3./7+1)6-2(,/5/2.*31301/0111+31/1140/1-+2323.1.67422+*220//.0/1+,605/-7.55204-/4233,34227,4.6-38--4.642%4-51,&830+/.304*618*2/13)12550241260126---3-22-41410-6*/2434.0,1/4101.01'525,33300--/245+33.*24431/2.5-12'326373/*14,2*0502..2216317/..16,5.1411/2424)3512+'.54.,3-60/30614/2.41-1/-1/2+1-1,22/.../7/2/1311226450445-424153432213421/325466,+0*132+5/4./6058-(-.535-(0.44330*2456124/&435055503425.-*0-1.#.00/'/742/2333-26)55.3-50600/01-+07/.13//051/,35.,.17,5(4,20/3,53/51214533.36225741-/1+.73/50*4'.4'+35/-+1)00302521*12,/43-60367552)4/,51+'130//-273,.40//07017/,36250010.430/2-413)36.123603075124/70-6510.52.3.0/.-/62120.4+3414100.'260141-,2.1736/0/021/2-1205-/.,)1.623..224*)131(/4863/0-30(01.4+3656*/356,+187.*1.4,542/2/133*.+112.134262-33(42348/./0434,6/50621.0231-*/54452533414/-)/41,31(562032.4/1+*1,56-/10,33140.,10-4*2442313134001*6351./.2/01.6-1/7-443/351,1(,10/(*21222,9/.3)10-105/6172425005/1.+80/1*.34/01*5624-/,16102--.6,353)12-,101,3.4+8.350/2/020063)-02163113301/44433603143+22/-/1+303/4.66.524/31.001-0-+/*351,9-./00-2242/*321,324377..*-80.3/1/41&6-.6221350321+-1+'.45./4//262503541--0+610/46*-/20/.030.*345514250'6/2/122/00)8*1,010/24'10*1445-./673.475-11/13/6+01-240,80610*4'-403401201003634-)0-421220+5/3-(/06181*3)22405533.25457414-5*0,56254523/06/534001)8/+//,56232-011./0012082540.,0/3521-//.-7,5360343/2605710005417*)200371+5//+425134.0*232-0-./11..4114,3531//1+40202,0./)21+.*-.014/116.4610(5750109233+/.20.4*0//3460/2136/+-2.6*161550//002-3/5183,34643003+203.00)342/.14+.40).3125.445351.-5,0.2/,6,,1-5230.00350222/34-1124-13.+.2-25532540,0+42.004-14314371.44-6/4-(5051/02/6201-0426003/(--55,1//(5225-.022/.0852404(32632'447/3/50.1.561/3/5550.23,45+.65$632-60/1/-8205*743,4+'*6/2-11.25.5-04-4.'43/-52/73.32107141321+.4412/310/6361.5,4)/5713-,0.3460410212-*05-.10)3255146(2/.00/2(21-2,0.6/30*50,/823522-0.0'-4)13.16.5/-/+33435005.*54,.33022612*4-310500.233543015/.5/0240*18)21*3/.(211/0/311'13221*10,14431//1+.1-/15.,01-.-0565023-3.,4%0+0.+53613+-/,2+4144/13-*32./&2336/5/)3015.+3/2*(83-,4234-,/3+.1(*14/51-3/.62620344/.-+21/6,2/4/201-/1,610-4623//2/,024-502(/154*65*&.4'204*30.-31//4144317(-24231-63./*1222232./4.2+535322201/3102333"
Returns: 
"This test case has 100000 nodes.  D = 7 and a = 0.9106890605104496.  There are 10000 queries."
Download
5)
    
"16 ,-.,*)+,,-,-,+*&.+,,0.,-+/.+.,,-,---.,,-+,//+.-,&*..+-...-*,-,-,-+..+.-,.+*.*-*+,+,,-.+.')+,..,-,*+*+,-,+.))./.,.,-..*/*,.'.+*++,,,+,+).,-.+-+*.,-/*+.+.,**----+0,/,--..+--.(*.*).-+*,++0,,+&++--/).++,*.),..)+,*.'+/-/+,,+,,--+.++---,...-+..+.,--/-*,.-*.+.-+.-,.-*.-**-/+*-.*/+.*-,/*+)-,.-(((-*-.---+-.,-+,*--.,..,--+)-/.-,.*,**,./-,.-/-/,.,*,,-+.+..-,--,,.-,...++++.+),..-(--,-+,*-),*,++-.,(-,-*--+-,.+-+,,./)*.-(.+(*-,+,**/,),-,*/),*,,/--,+,-.)-.,-,.(+*-*,/,-..,/.,,***/+,*+,-.*-,./.-/-,,,)+,+/+/-,..,/---,,+++-,,.*-+-,,--,,-+,+,-,+,+,+-,-.---+*-..**,.---.-(,+-,+-.,,...+,+,---.-+--./.).-,,-,.-+.+*/-,....+.+.,-/--,-,,,)-,,--,-**,*+.+.,,,.--..,,/+.)(,,(,--.,*,-,+-(.-+-+,,.-,.--)..+..,),*.-,.-,*/*-),,/++-,----,,-.--+---,*,+/.,+---++-,,,.,.--(-,..-,+-+..*,,-.,+,+*--.)-&-,,--,,-.,.,.-,--+(*+-,,.,-.-*,..,*,..-.+/+-*/*--,-.+,,+,,---,)*.,.-/./....).-./-.-.*-.+'.,--,.--+...+.+,,,-,,*,*,--,,/,,,*++.-.-,++-.--.-.+///+*.,/-*),-.,*,,-..-.,+---*.-.,+/-,.'+-+,---...+,,----*.-/,+/-/,).*+----+-/--.+/--/-*,+..,+-,,/*+--/-,-++-.,++../).,---+++-,/-,-+-,*)+.+,--/,-(-+/.,,*--++.---.+.-,-.,,/-/-.+-..-,--*-..+,+.-,.,,0,,-+--+-++.+,-,-../-,/,+*+,,--/,--+--,,,,/&,/-.,.-,.*),+/-,--*.*-+..+,,.+,..-,,,+--+..*--).-,,--.+-./,--+,,+--/,--.-,*.*.++-+,+*0)(--,,-*--.-,*-.,+.--+..,,),,-+.-/--*.,)--*..*)--..,+.+.*.**.+,--*.-,-+,-+*+-(*..(,'*-+,.,.-+,/+)---,,.(+,,**-.,,/.+.+'---,,/-*-.//-+*-.*-+*,,+*..-,,/+-*+-.,---+,,',.++,+--..-.*)-+.-/(+----/,,,-++*-.-,/+,+---*+-&.-.(.*/-+--,.-++,+.-.*----,,++,,),.-*,,-(+++.*,).+.--,+--+-.,.,+.-+-*--+-.(..--.),(--...-+-+.,,----.----,-,.,,.--+++-,.+,,.,),,.,,,/+--+-.-,-+---*./+-/-.,+--,----*,./+*/-.,*-*-/,-,..,..),.+*-.,-.*-+*----.-+-,-,0,.+++-,,,+,.,..+,.+.,--.-+-,-,+,/*...+.-,,,/*,-,-,.,-,--.+-.,---).,-,+,./)-,,.,*,*/),)*././--+-+--),-.++/-,*-,+-.+.-.).,.,.+,,),--.+/&+..+,-++0-.-,(,,.,-.,,---*-.,*.+-,+-*--+.,,.,/-,,++---.+,-/,,)./-,---/.++--..-+.*-+*-/.---*)--*,,-*,--/-)/+..*.,,--,,,-,-+(.,/*,--.--(.*.+..+,,+-,-*.,.-,.-.+,-,--.+-*---*,-+*.,+-,+..--.+,-+-.,.-.,*,-+---,,-,**.,+.-&+'+*(,,*-,-,/*.*+++,.+*-(..*/-++--*.,,.,)-*,,--,.*-)*..-.+-.,-/-,)*-,./-.-.-.--*.-/+-..)+,-+.+*,.,-(.,--.*--.),*,*.--,--,-,..---,,,-,.-..+*/-+/+./)+.-,,.././)-*--,/-,--+,-.++,,,-/,,),.(*....+.-.,.(---(,-.'-'./.,/-,+-+,-*,---.,,/-...,.-,,/.,---..-+,)*,+./.+--.,..-.,,..-.,*++-**+*.-/-,..+/..--)./+.--./-.+,(-,+.,-.....*+).*--..,+*-*+.),*-,--,)-**..+-+-++-*.-.-,,-+-*+-+-*,..,/.*-+-+.-,+.-,,/,+--..+.*/./,+--,-,+.,/-),+*)----+--(*.,-,.-,/./,.(-,+.,,-/-..,*,+.*,.,+,*,--+,..,+.-,/+/-++),.-,)-,-,,+-+-+-,.*,.,..,-,,,',*,-++-.,/(..+.-,)*,--*/+--,+.-,,-+-/-,,/-),--.-,--',++.).,/-.+-.,'+--,.-.-.),,.--.+)+*+-,,,+---+-..-,+&0-----,--,-./+-,-/.-.,,+.,*,+.--.,/-,-,)+.-*--)*-.+,,-.*-++-,*.-+++-+,,,,+,,+-,,-(/+--/-,-..-+-,-,-,*--+.(.,.+-,-+)+(-,*-.-,/-+/+,,--,)'--,.*,-..,+(-)--,,-,.-+.+--..,,-/.'-././*()/,*,.,-*,+.'/.,//,-,+,.,-,,,.,)'+,.,+-/..-+,,.,.-(.-..,,-*,*-(*--+-.)-,./,---,/()-,.,--*).+-+*-+,...,/,-+.*+,.+.))-,*-,-**,+./.+,,,/,,.--*),*,--,--/,-,-.+-.*,/.+,,-+.///-(,),.+.-,/-.-+--*,..*/.+++)*)-*,./-,.)-(.0--.,+,--,-,---+-/..,+-,-.,.-.++),-,.,+,---,+.),.+../.,,-,/,-*+.-.-/--/-*,+.,*..---)--+,.-.**,-/-*--*,)..--/.,/..-,,**(-,-.+*-+.--.,.---.-*)-.+,*-,.,*-++-,-.--/..-.,-)/+.+.)-*+**++-,-.++./,+.,.-+,,.-*/.-,**.,*---,,..//.-,+,.+-//--.,-/,-)-.,.+,,,+-..)+,/+.)+*.-*-+,,,-*-.,.,,/,+++-.+*-,--.-,--,-...,/.-)*'(-/.&-,*/-,*,-,,.+.,-.+,,+../-+-*+,)-*..('/%.,--,/,,,)-...--,,,+.,/..,-,-,,.,,.--+.+/',*,+-,)/,*./+*-0*+-+.--..-,-*-,.-.-+,*/-+-,-/*..-.-))0+-,----+,(--.*)-.-+-,-(-+,(.+*,.-+/,,*,....*,&++)+--'-,,+,.+',-,-/-..,++-)+-.++*-,-..,0+*/+,-+,,,.++,--..--.,/-../+-*--.(,./,-.,+-+.,---/.-./.)-+--.*-&+.--.-,..-(*+---'+++,+,----(-.*,..+--,-,/-++,.*,-,,+.,+--,-.+-,*.---/,.++-+++)-.+++-,.-.-/-.-.+,/.*--,.--,./--,+*)+,.-++)-*,)-,,,,/.,+...-.-.-+,0-+,,-.+..-+-,,/-'--*.-+-,.-).+..-+)*,--*,,))-,++/.-**,*--,,-,+*++,-.-,,(+0--,+-/+*--.,+-)-+,*)++)-++%-.)&.+-.(*,--)+,+...)-//,-.),.-),,*,+--)---,,+.-,,-,,-+,.(,,/.,-/,,--/,-,,,.),.-*-/+-.*.-,-+,,-.,-,++,--*-)+..,---+,*+.//--,.,-,+/,-/--+.*.)(,.,.*../),,+.-,+-*--*,,-(-+,+-.,-*-..+-+-/-.*.--./.*+*,+-*,,+-,+.+,,-.-.)-,)/*.-+,,,,-+-,--+,(.+-,/.,/,+,-,+-,--.--*,*+-,-)+,.,-++,-,.---/+--+-/,,,**,,-,,*,-+,--,.-,,..--,,),*,.,/--,,*.,),--+.-+/-)+-**-.+++--,+-)..,,)+,--/.-++.,*,-),+,/..,-,-,----,--,.,,)-/*,0..,++-.-+-.*,(-,---,+,/.-+-.+-.--.+.*+,*(+-,-)+-.*+,++++,*-.**,--,.--,-)*---*+--,-.&--++,+.--.+-.+.,-+,--)+++-(--.*,,,/./--+---.,-.----+.+,,,,'--*,*-.-,*)*,'+-,./*-*++-+++..+./--+,--/.+,.-*,-.,,--.,*/.*-.(+,*--,-,--.(-.(,,*,,+)/+.-,,-/,,-,,/-+.-,-),-),,/-+.,-----,,.-'-,,,*.-'/,,-.,--,-..,...-,(+-.++,,,*+.,.-,++,.,-+-.--',*-*.++,/,-.**)-,-)-./)++)..++)..-/-*,-(*-,+,.,/,-+'--+-,)---.,++/.,,.,--,*+--*.-+,+/--.--,-*+)-.+*,-,..,-.-).-..+.+.,*)++.,,....*.,-)+.,..*.,)++.-,+..-,*.)*+.(,+//*/,,..,/.,-/*----..-+-+,++.+)-.*&.+++.),.).---,,--,-+.-*++,,...*/.*/---.,,,,-,-)-.,.,*-,/'+-+.-/-.,+,.,-.-+-+,.*--.+--+,.+*.,,,+,,..+,,--...--..,.'+....-*-/+/+,.----..-------,-+,++,+.,),)/--,.-.--+,,+-)&+/+.+--/--,+,/+.-,++++,--,-/)-+)+-(-++***,,*+,+).,.)--.-'-*--,+-.//,-+-.,-*,/.-)/,----*--/,,---...+,-+.),-&-..--,+..----+,,.-.+/--+----*/,,+*---*-/.+.--*.+--,,*.*/+,-,*,,(,-*,-...+-*/,.-),)-.--++,.-,,+.-/+.+,.+,,-./,,-,..,,-,+,.-+*-,--+-.+.,.--*..,)--,.*.),-,)./-*-+-+--,,.-,./--,--,.,-,,*..+-,.+.-.&0++--,,*,++-++..,,+++)-,.,.*-.0+.,,./++-,../-/-&/,-.+--),-.,*.-.-,..,-)/+-.,)/),--,.*,,.,)--*-+,)--+,*.+----)-.//+-.---')+,+./+-)-/)*-/++.-.,.&+,,+-)-,+-+0*,,.,,+),++-+(,+).,+,,/-,,.+/(-.+-*)/,/*-)/,*,+-,,--+,,.-*.,-.-,.,..---)-.--.*,-,./-+,-)+..,,,+,-..-.,+-.,/,.*/)-+-*-..*,,--,-.---+--(/--.-.-.()'+.'*+,.,.-,-+,+-&/,.+-.++--.--+,/+,-.+..-.,.(-+,++-.,..+,,*+++.,--+.).,+.-..+.+,-.-.+,+,.+....0+*---./+*,,.**-++*.--/..+-..+(+,--/'--,..--,+-*-.*,+..-.--,+.+,-+,+.,*-/*.*,--,-*+/,,-..,.+-,---/*,*,.-*+,+/,+,+,.)-),.--,.+-*,.+.-,+-,-),-+-+/*,+*+*)--.-.-/-)+,,--&..(---..-,),--/.,--+-,,.+*--0.-+,--,.++-,.,-+*-0+,.,.--,--,-++.*.),+,/.+-,+/---,/++.+..-,.--,--.,.+./,,.---*(+./*.-,,,.+--/--.,+,.)//-+.---).,-.-.-+&/-+--,,+*./,+.-+/.,-(+.-...+,++/--+,+*,,.,-+.,,-..,,,.+)*,-----.,++,-,-/*,-/,,,+,-.-.*,--)*,/(-/..-+.,,,,+.-+-.-+.-+-,+-+)-,-/../-,-/,--,,*.*,++-.-++-.,.-..*----.--,,*+(+.)*--.,.-.)..,.-/.(-.-,,,.*++-.+-/.-++..**.+*..--//,,,*+--,-,+,+-++.,-...,-,-..--..,,,-+.--.-.,*,-,-(,)..,,---***),.--------/+.,-,'+--.-,,-.,+,-,-*)/-**----+.'.-.,'--++-,-+----,,,),.,++,,,+/,,/-(*)+**,,/+..+)).-----*-,,*-.(,.,,,+-,--*+*--.-+,.++,.,+,---*,-),,-,,-..)/-,,*,++.*)/.)+-+-*,./-.--+--/,.)-++-*//.-.-.-.-+-,--.*+-/*++,,-,,('.+-.',-+---,---..-,.*++-.--,//,-)+-/.,-.,,/-,.*,,(-)-++-.+,-++*.),-+-,+-+-.-*,-*).-,,*-***+,,-,----,-,++.),,....--.-,-.-,,./.++.-.-/-,..-.+,,--,-+,.-.,.,+--,+.)/--*,//+-+-+---./-(.,++++..+-,,-*+,,..-,.-,-*.+-+)-/-/+,-...,./*,+..--.-,-.+-*--..)*(---/,*-(./.*,,-//.+-/.++,.--.-.-,,*-,+,*-,--,-+-.)--.-..+.,+-,-.-.,.,--,..-,+-.+++,,,,,,,,*+.-..-,,-.+.-+-,.,--,+./-.-./...---/,,,/----+--+-.,-0+,.,,).,,-*-,,-++.-()-+,+*,*,,+-,+..,..,-*-,..--./,+.*.,.,.)().-.----..,./*))+...$*+,+,----/,,.-..(++,.*-*.-+--.*/+.*-.,-**,.,-.+.+'-,)-,',*,-+.-./,,/*+,*-',,/-.-,,+.----*+++*/&)+,.,--.+..,,-(,),,-.*---,-+-+-,'-...+.,--/...,*-.-,.,-/--.++...,..****-+--*--,-)++,)-..-..,,.*--/-+..,-,.*,..//,+,++-)+++,-,---)--/,.*-+,,.,++(.-.,--/..-,-*,/++-+.*,-.,,,./-,+...,(,--,,*.-,,,,.-.-+++..-+,.,-.,.,/*,-&,-*+-,,,-+/----'--**,)),-.+/---(,-..-,---.,*+--(..&-*--,**,.../,+).-,)---*-,--)----,,-+-/..-,--,+,../---+.+..,+.-.),-,)*,,-),)--+,.,+-.*-.-,*-.*,./,*+---,*,&,,0+*--.+,,+,.,,,),'-,++/,-.-+,-*,.+-..,+(*,...+--*.-.,---+-.,,.+---,+,*.+++,+/,,-,+-,.---,,-*+.(--.,*,---.------+.+.+)-..--**+--.*.*(*.)..+.-).-..-,--/.*--*.+-,/.+--../.---*+.-,-,-,..-*,,--+,)--/---.-,,.,,+,..*--.-./-,-+.,-./+..+*.),.++-.--+-./+-.-.-.---,/),....+,++).',,,--+-/,-+,.,,*&.,/+-.*,),...-)-,*+,-+/,+--.,+,+,).,)).-,+,,-,-,--.+,,/,/---/+,.-0*-/.,-----.---(-,-+-,,-,*,+-.,.-..+-+.-,,-,-+,--..-*--+---,,**.+,-,*..+,+---,-,,/,.-.,+---..,,*-----.,-++,,-,---,--,&+,,+-././,--.,/--,--,),....,)).+/-).+--+-,+.+*-)---.,-,-+-+-*-,,,+/.-+.-,+/,-*+-,,,.--,/..++-,,.-*---,*,+,.,-.',-/,+*-,*-++--.,*-*-----+--.,.,*---+,-*,-,-'--.,/,.--,*.,------,--,''//+--.).-,*,-,+--,/-).().+.+,*+..----/-+---/-(.,-.*-.+-*,/*-,--,+,*,---+,-+.+,)--.*(./,,--,,-../--(+*,,.-+.(.+-+(-+-*,-)++.,-,+,(+)-.-,*--,,*.-+-.-,.+.+-+-,++..(*&,)-,,---,/-(,.+-.,+-+-((**--)+.-.,+)+./-++-.).,..+-.*-*-,+*,-*,-.,-/+,+.+)---)...,./*,*.,-,.--./..,-,)-),,-.-.,/*++-.*-.+/,+/+-,--/+-++.-,+./-+.,+--,,-,.-,)*,-..--.-.-.,'++,..,,*.-,+*.-/.-+.,,),--,,),-..-,,-.,+-+,,.).*-,*.*-,/+/*.++).---)++,..-)-+-+.----+./.+)-,,,--...,--.,-/+..&+.,--,--./..-,.-+.,+,.-0,+-,+*+---+-,..-+,)/--).,.,-.+),/,.+-----.-,'.+.(,,((--,-+,-,.+)/,/++./*,+)..,-.$,.,.,...)/&--,).-+-0/,,,-,**.)++(-)-..-+.*.-..-/++..,-,*,,/,*+,+-*..+,**-,,+-.+(*-(-.--(-+,--.**-.,+--.,,/-.),/,-,-+..-,.,,-...,-+-++(,-,-.+,...(,*.,/.0..'-+,.-+-+,/-*,,.,-.--,-,-,,.-.-./.--,,+,.*,+(&+-.,/,--.+,-.,,,,+*,,--+*-'+.*-/+(-,..,-,-..+,+,.,,..*,-/.,,-,,-,.,+.-,+-/*/+++/*.,..--.++-+..+.*,-,0-.-++.+,-0.,,..++*/0**,-.+.)*--//***,,-/.,-,....-+--,/+(+-,.-.+.--.--,-/-..-,+.-+,,,.--.,*/*-.-+*-.,,,-.-*-.,.,.,-)-,,-----+.-,,+/*,+--*-)*..-,../+-,)-.+-.,,,*..,--+---+,),-.,+-.-+,,./+..,+,.,,.,.-...-.(-.0--+.-.'+,..*-..,,)+-(.*)+++*..*,*-,--//+-.,-,,*--,,/,+//,--,+-+,**-,.++,.,)*+,,,)*.+,+-..---,/-+.-,+.-.,+.-*-+,-.-,-,++/+)-/-.),,.*'-..-../.,,+.-*/.,-..,,-,,,+*+,.,-,..,..,--,--(,.+./-.*.,.++,+.'.--/-,--,-,0--.**-,----+(+,+*-..--,.,)-+/,-(-.,+,,,,-+--,-,-,,--.-*-+.-,--,.+)*+,,-,+.,,,++'/.-.+.+.-++,-)+,,---,-*.+---,-.--,,.,-'-,-,..,),/..+-*-,,-,+-.,/-+-),.--,-,/+.*-,.+,-.()-*--*.++,,*/*-)----,/.-,-.----,..-,,*.+(/*,*+---./+,++-+*,,,*.0-+-,-.*)'+-..-.++-,,-,+,+.++-,--+-/.,..,,/,-/)+,.-)-.-,-/-,.+,--,),,)/+(*-,,+,,.--++.-/.+,,.,-*',-,.,,-)./-..--)-,.*/+(-*/--.)++)-*+*,-,.+.,++-,-+..)*.,..(,.)-+.0.,,+)-,--,.,,-)-,*-.-*(,,(-.-+).-,---)--+.-+,,--.,--+*--**,,)++++--.-,+-,*-'*,+(,*-,-+.-----,*--,.+(//,,+,..-,-.,-*+*-,,-/,.+*..-/,+.*-/,,++,-,.-/,,+-,)-)+-..,-.,*+,+-.*..,.-.-.)-/-*.-,.++--.--&-+.)+*+/-+.,,,-,),--+)/,).-,,,,/-,-./.,'---.+.,..*-./-.,..*.,%-,,*-,/--,-,/,,,-,./-.,.-,...-/,+-)/+--,-."
Returns: 
"This test case has 1000000 nodes.  D = 5 and a = 0.5126586954905619.  There are 10000 queries."
Download
6)
    
"17 &&&%&&&&%%&&%&&&&&%&&$&%%%&&%&&&&%&&%&&&&&&&%$&%&%%&%&&%&&&%&%%&&%&%%&&&%&&&%&&&&&&&&%&&&&%&&&&&&%&&%&%&&&&%&%&%&&%&&&&%&&&&&&&&&&&&$&%%&&&%&%&%&%&&%&&%&&%%&&%%&%&%&&&&%%&%%&&&%&&&%%%&&&&&&&&%&&&&'&&&%&&&%&&&&&%&&&&%&&%&&%&&%%%&&&%%&&&%&&%%%&&&&&&&&&%&&%%&%&&&&%&&&&%%&&$&&&$%&%'&%%%&&%&&&&&&&%%&%%&$&&&&&&%&&&&&%&&&&&&%&%%&&&&%&%$%&&&&&%%&&&%&&&%&&%%&%%&&%%%&&&&&&%%%&&%%&%%&%&%%&%$&&%&&&%%&&%&%&&&%&%%%&&&%%&%%&%&%%$&&%%&$&&&%&&&&%&%&%$&%&&&&%&&%&%&&&&%&&&%&%%&&&&$%&&&%%%&&%%&&&&%&&%&&%%&%%%&&%%&%&&&&%&&&&&%&%%&&&&&&%&%&%%%&&&&&%%%&&&%&%&%&&&&&&&&&&&&%&'%&&&%&&%&%&&&&&&%&%&&&&&%&&%&&&%&&&%&%%&&&&&&%&&&%%%'%&&%&%%&&%%&&&&&&&&&%&&&&&&%&&&&&&%&%%%&&&&&%&$&%&&%&&&&$%&&%&&&&&%%&&%&&&&&&&%%&&&%&&&%&%%&%%&&&&&%%&&%&&%&&&&&&&%&%%%&&%&&&&%&&&&&&%&&&&&&&%&&%&%&&&%&%&%&%%%&%&&&&&&&%&&&&&&%%&%&&&&&&%%%&%&%&%&&%%&&&%&%&%%%&%&&&&&%&%&&&&%&&%&&&&&%%&&&%&%%&&&&%&%&&&&&%$&&&&%&%&&%$%%&&%%&%&%&&%&%%%%&&&&&&%&&&&%&%&&&%%%&%%&&&&&&%%%&%&&%&&&%&&%&&%%$&%&%%%%%&&&&&&%&&&&&&&&&$&%&&%%%&%&&&$&&&&%%%&&%&&&%&&&&&&&%&%&&&&&$%&%&&&%&&&%&%%%&&&&&%%&&&%&&&&&&&&%&&%%&%%%%&&%%&%&&&%&&%&&&&&&&%&%&%&&$%&&&&&%&&&&%&&&&%&&%&%%&&&&&'&$&$%&&&&&&%%&&&&%&&&&&&&&&&%&&%&%&%%%&&&%&&%&%&&%&&%%%&%%&&%%&%%&%&&%&&&&&&%&%&&%&&&%&%&'&&&&%&&&%&%&%&&%&&&&%$&&&&&&&%&&%&%%&&$&%&%&&&&&&%&&&%&&%%&%&%&&&%%&%%&&&%&&&&&&&&&&&&&&&&%&&&&&&&%%&&&%&%&&%&%$%$&&%&&%%&&&%%&%&&%%&%%&&&&&%%&&%%&%&&%%%&%%&&%&&&&%%&%&%&%&%&&&%%&&&&%&&%&&&&&&%&&%&&&%&&&&&&%&&&&&&&%&&$&&%&&&%$%&%&&&&%&&&&&&%&%%&&&&&&&%&%%&%&%&&%&%%&%&&&&%&&&%%&%&%&&&%%%%&&&&&&&%%%%%&&%&&%&&&&%&%&&%&%&&&&&&&&&%%&%&%&&%&&%&&&&%&&&&&%&&&%%%%&&%%%&&%&%&&&&&%&&%&&&&&%&&&&&&&&&%%&&&&$%&&&&&&&%%&&%&&&%&&&%%&&&&&&%&%%%%&&%%&&&&&%&&&&&$&&%%&&&&&&&%%%%%&&&&%&%&%&&%&&%%&%&&&&&&&&&%&%&%&&%&&&%%&&&&%&%&&&%&&%&&&$&&&%&%%&&%&%%%&%%&&&&&%&%&%%&&&&&%&%%&&&%&&%&%%&&&%%%&&&&&&%%&&&&&%&&&&&%&&%&&%$&					
				
			
						

CarolsSinging

Brute Force, Graph Theory



Used in:

SRM 331

Used as:

Division I Level One , Division II Level Two

Writer:

slex

Testers:

PabloGilberto , brett1479 , Olexiy , marian

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7280

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10011&pm=7280

Problem Statement

    

When the Christmas dinner is over, it's time to sing carols. Unfortunately, not all the family members know the lyrics to the same carols. Everybody knows at least one, though.

You are given a String[] lyrics. The j-th character of the i-th element of lyrics is 'Y' if the i-th person knows the j-th carol, and 'N' if he doesn't. Return the minimal number of carols that must be sung to allow everyone to sing at least once.

 

Definition

    
Class:CarolsSinging
Method:choose
Parameters:String[]
Returns:int
Method signature:int choose(String[] lyrics)
(be sure your method is public)
    
 

Constraints

-lyrics will contain between 1 and 30 elements, inclusive.
-Each element of lyrics will contain between 1 and 10 characters, inclusive.
-Each element of lyrics will contain the same number of characters.
-Each element of lyrics will contain only 'Y' and 'N' characters.
-Each element of lyrics will contain at least one 'Y' character.
 

Examples

0)
    
{"YN","NY"}
Returns: 2
Both carols need to be sung.
1)
    
{"YN","YY","YN"}
Returns: 1
Everybody knows the first carol, so singing just that one is enough.
2)
    
{"YNN","YNY","YNY","NYY","NYY","NYN"}
Returns: 2
Singing the best known carol is not always the optimal strategy. Here, the optimal way is to pick the first two carols even though four people know the third one.
3)
    
{"YNNYYY","YYNYYY","YNNYYN","NYYNNN","YYYNNN","YYYNNY","NYYYYY","NYNYYY","NNNNYY",
 "YYYYYY","YNNNNN","YYYYNY","YYNNNN","NNYYYN","NNNNYY","YYYNNN","NYNNYN","YNNYYN",
 "YYNNNY","NYYNNY","NNYYYN","YNYYYN","NNNYNY","YYYYNN","YYNYNN","NYYNYY","YYNYYN"}
Returns: 4

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

VolleyballTournament

Simple Math



Used in:

SRM 344

Used as:

Division I Level One

Writer:

Petr

Testers:

PabloGilberto , brett1479 , Yarin , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7252

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10668&pm=7252

Problem Statement

    

The common method to print the standings for a volleyball tournament is to print the number of won matches, the number of lost matches, the number of won sets, and the number of lost sets for each team.

Each match consists of three to five sets, where each set is won by one of the teams. The first team to win three sets is declared the winner of the match.

You are given one row of the standings table. That is, you are given an int wonMatches, denoting the number of matches won by a team, an int lostMatches, denoting the number of matches lost by that team, an int wonSets, denoting the total number of sets won by that team, and an int lostSets, denoting the total number of sets lost by that team. These numbers represent a possible tournament outcome for a team, and you are to reconstruct the results of all matches for that team, and return them as a comma-separated list, sorted lexicographically. Each match in the list must be formatted as the number of sets won by the team, followed by a dash ('-'), followed by the number of sets lost by the team. The possible outcomes for a match are "0-3", "1-3", "2-3", "3-0", "3-1", and "3-2" (all quotes for clarity only). If multiple different result sets are possible (sets that are reorderings of each other are not considered different), return "AMBIGUITY" (quotes for clarity) instead.

 

Definition

    
Class:VolleyballTournament
Method:reconstructResults
Parameters:int, int, int, int
Returns:String
Method signature:String reconstructResults(int wonMatches, int lostMatches, int wonSets, int lostSets)
(be sure your method is public)
    
 

Notes

-The returned string must not contain spaces.
 

Constraints

-wonMatches and lostMatches will each be between 0 and 100, inclusive.
-At least one of wonMatches and lostMatches will be greater than 0.
-wonSets and lostSets will each be between 0 and 500, inclusive.
-The numbers given will correspond to at least one possible result set.
 

Examples

0)
    
3
3
9
9
Returns: "0-3,0-3,0-3,3-0,3-0,3-0"
1)
    
0
3
6
9
Returns: "2-3,2-3,2-3"
2)
    
3
0
9
3
Returns: "AMBIGUITY"
It could have been "3-0,3-1,3-2" or "3-1,3-1,3-1".
3)
    
1
1
4
4
Returns: "1-3,3-1"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RemissiveSwaps

Brute Force, Graph Theory



Used in:

SRM 354

Used as:

Division I Level Two

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Yarin , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7248

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10711&pm=7248

Problem Statement

    

You are given an integer N, and you are allowed to perform the following operation: take two nonzero digits of N, decrease each of them by one and swap the resulting digits. For example, if N is 166, you can reach the following numbers in one operation: 506 (swap '1' and the first '6'), 155 (swap the '6's) and 560 (swap '1' and the last '6'). You are allowed to perform the operation zero or more times consecutively. Return the largest number you can reach.

 

Definition

    
Class:RemissiveSwaps
Method:findMaximum
Parameters:int
Returns:int
Method signature:int findMaximum(int N)
(be sure your method is public)
    
 

Constraints

-N will be between 1 and 1,000,000, inclusive.
 

Examples

0)
    
166
Returns: 560
The example from the problem statement.
1)
    
3499
Returns: 8832
The following sequence of operations is optimal: 3499 -> 8492 -> 8832.
2)
    
34199
Returns: 88220
The following sequence of operations is optimal: 34199 -> 84129 -> 88123 -> 88220.
3)
    
809070
Returns: 809070
No operations can increase the number.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

NewMagicSquare

Math



Used in:

SRM 351

Used as:

Division I Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7247

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10675&pm=7247

Problem Statement

    

You are to populate a 5x5 square with each of the numbers between 1 and 25, inclusive. The numbers in each row must be in increasing order from left to right. Some of the cells are already filled in, but no more than one number per row. You must fill in the remaining cells.

You will be given a String[] square. Each row is given as a space-separated list of cells. Each cell is either a number written with two digits (numbers less than 10 have an additional leading zero) or two '?' characters which represent an empty cell. Your method should return a String[] in the same format, but with all the empty cells filled in. If there are no arrangements possible return an empty String[]. If there are several arrangements possible return the one with the smallest first number in the first row. If there are still several arrangements possible return the one with the smallest second number in the first row, and so on.

 

Definition

    
Class:NewMagicSquare
Method:completeTheSquare
Parameters:String[]
Returns:String[]
Method signature:String[] completeTheSquare(String[] square)
(be sure your method is public)
    
 

Constraints

-square will contain exactly 5 elements.
-Each element of square will contain exactly 14 characters.
-Each element of square will be a space-separated list of cells.
-Each cell will be either a number written with two digits or two '?' characters.
-Each element of square will contain at most one filled cell.
-All numbers in square will be between 1 and 25, inclusive.
-All numbers in square will be distinct.
 

Examples

0)
    
{"?? ?? ?? ?? ??", 
 "?? ?? ?? ?? ??", 
 "?? ?? ?? ?? ??", 
 "?? ?? ?? ?? ??", 
 "?? ?? ?? ?? ??"}
Returns: 
{"01 02 03 04 05",
"06 07 08 09 10",
"11 12 13 14 15",
"16 17 18 19 20",
"21 22 23 24 25" }
You are not limited by prefilled cells. The answer is the lexicographically smallest square.
1)
    
{"?? ?? 20 ?? ??", 
 "?? ?? ?? ?? ??", 
 "?? ?? ?? 05 ??", 
 "?? ?? ?? ?? ??", 
 "?? ?? ?? ?? ??"}
Returns: 
{"01 06 20 21 22",
"07 08 09 10 11",
"02 03 04 05 12",
"13 14 15 16 17",
"18 19 23 24 25" }
2)
    
{"?? ?? ?? ?? ??", 
 "?? ?? ?? ?? 24", 
 "?? ?? ?? ?? ??", 
 "?? ?? ?? ?? ??", 
 "21 ?? ?? ?? ??"}
Returns: { }
You should place four numbers greater than 21 into the 5th row. There are four such numbers - 22, 23, 24 and 25, but 24 is already used in the second row.
3)
    
{"?? ?? 15 ?? ??", 
 "02 ?? ?? ?? ??", 
 "?? ?? ?? 07 ??", 
 "?? ?? 16 ?? ??", 
 "?? ?? ?? ?? 21"}
Returns: 
{"01 03 15 17 18",
"02 08 09 10 22",
"04 05 06 07 23",
"11 12 16 24 25",
"13 14 19 20 21" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Terrorists

Graph Theory



Used in:

SRM 334

Used as:

Division I Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy , marian

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7246

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10658&pm=7246

Problem Statement

    

There is a direct bidirectional road between every pair of distinct towns in the country. Terrorists want to blow up enough of these roads that there are at least two towns that are no longer connected to each other by any direct or indirect paths.

You will be given a String[] roads. The j-th character of the i-th element of roads is a digit representing the cost of blowing up the road from the i-th town to the j-th town. Return the minimal total cost required for the terrorists to achieve their goal.

 

Definition

    
Class:Terrorists
Method:requiredCost
Parameters:String[]
Returns:int
Method signature:int requiredCost(String[] roads)
(be sure your method is public)
    
 

Constraints

-roads will contain between 2 and 50 elements, inclusive.
-Each element of roads will contain the same number of characters as the number of elements in roads.
-Each element of roads will consist of digits ('0' - '9') only.
-The i-th character of the j-th element of roads will be equal to the j-th character of the i-th element for all pairs of i and j.
-The i-th character of the i-th element of roads will be '0' for all i.
 

Examples

0)
    
{"0911",
 "9011",
 "1109",
 "1190"}
Returns: 4
The best decision is to isolate towns 0 and 1 from towns 2 and 3. So, the terrorists should blow up roads (0,2), (0,3), (1,2) and (1,3).
1)
    
{"0399",
 "3033",
 "9309",
 "9390"}
Returns: 9
The cheapest plan is to isolate town 1. So, the roads to blow up are (1,0), (1,2) and (1,3).
2)
    
{"030900",
 "304120",
 "040174",
 "911021",
 "027207",
 "004170"}
Returns: 8
3)
    
{"044967263",
 "409134231",
 "490642938",
 "916036261",
 "634306024",
 "742660550",
 "229205069",
 "633625604",
 "318140940"}
Returns: 27

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ByteLand

Graph Theory, Greedy



Used in:

SRM 345

Used as:

Division I Level Three

Writer:

rusolis

Testers:

PabloGilberto , brett1479 , Olexiy , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=7239

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10669&pm=7239

Problem Statement

    

The Kingdom of Byteland consists of several cities connected by bidirectional roads. There are castles standing in some of the cities. Byteasar, the King of Byteland is unhappy with his kingdom's defensive power, so he decided to build k additional castles (he can only afford that many).

Whenever one of the cities is attacked by the enemy, the army from the nearest castle must come with help. The enemy is smart, so it will always find and attack the city that is the farthest away from its nearest castle. Therefore, the distance from the attacked city to its nearest castle must be as small as possible. Your job is to calculate and return this distance, assuming that you can decide where to build the k additional castles.

The cities are built in a specific manner. Each city has a main gate and several other gates. Every gate is connected to another gate by a road. It is possible that two gates of the same city are connected (see example 2). For defensive reasons, every road has exactly one main gate on one of its ends. Please note that every road can be traversed in both directions.

The road going out of the main gate of the i-th city leads to the road[i]'th city and is distance[i] miles long. The int[] castles contains the 0-based indices of the cities in which a castle is already built.

 

Definition

    
Class:ByteLand
Method:buildCastles
Parameters:int[], int[], int[], int
Returns:int
Method signature:int buildCastles(int[] road, int[] distance, int[] castle, int k)
(be sure your method is public)
    
 

Constraints

-road will contain between 2 and 50 elements, inclusive (let's call this number n).
-road and distance will contain the same number of elements.
-Each element of road will be between 0 and n-1, inclusive.
-Each element of distance will be between 1 and 10^6, inclusive.
-k will be between 1 and n, inclusive.
-castle will contain between 0 and n-k elements, inclusive.
-Each element of castle will be between 0 and n-1, inclusive.
-The elements of castle will be distinct.
-It will be possible to build the castles in such a way that you can always reach a castle from each city.
 

Examples

0)
    
{1,2,3,4,0}
{1,1,1,1,1}
{}
1
Returns: 2
Building the castle in any of the cities results in the maximum distance from a city to a castle being 2.
1)
    
{1,2,0}
{1,2,3}
{2}
1
Returns: 1
2)
    
{0,1}
{1,1}
{1}
1
Returns: 0
3)
    
{0,2,0,0,2,2,8,3,8,7}
{10,9,1,8,1,3,7,2,8,1}
{3,4,6}
3
Returns: 3
4)
    
{1, 0}
{5, 10}
{}
1
Returns: 5

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TurtleGraphics

Brute Force, Geometry



Used in:

TCCC06 Finals

Used as:

Division I Level Two

Writer:

radeye

Testers:

PabloGilberto , Olexiy , Jan_Kuipers , Andrew_Lazarev

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6877

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10136&pm=6877

Problem Statement

    

Your new graphical programming language Honu contains the primitives 'L' (turn left), 'R' (turn right), 'U' (turn up), 'D' (turn down), and 'F' (move forward), to describe the actions of a trail-leaving turtle in the three-dimensional sea. Only the 'F' command actually moves the turtle, and it always moves it one unit forward. All other commands simply change the orientation of the turtle. The turn commands all are with respect to the turtle's current orientation. That is, 'R' means the turtle turns towards its current right side; 'U' means the turtle turns towards where its shell is facing.

In addition, commands can be repeated if they are immediately followed by a single digit from 1 to 9. So "F3" moves forward 3 units. There will not be adjacent digits in the command string. Digits may only follow the characters 'U', 'D', 'R', 'L', 'F', or ')'. The repeat count only applies to the immediately previous command, so "FF3" only advances four units.

Commands can also be grouped by parentheses. So "(FRFL)5" traces a zig-zag line, repeating "FRFL" five times.

Parentheses can be nested, so "((F2)2)2" moves forward 8 units.

Given a sequence of these commands, your method must return the Euclidean distance from where the turtle began to where it ended up.

 

Definition

    
Class:TurtleGraphics
Method:distance
Parameters:String
Returns:double
Method signature:double distance(String command)
(be sure your method is public)
    
 

Notes

-Your return value must have an absolute or relative error less than 1e-9.
 

Constraints

-command will contain between 0 and 50 characters, inclusive.
-command will consist only of the characters 'R', 'L', 'U', 'D', and 'F', '(', ')', and the digits '1'-'9'.
-command will be properly formatted according to the description above.
 

Examples

0)
    
"FRF"
Returns: 1.4142135623730951
Going forward, turning right, and then going forward again leaves the turtle at a distance of the square root of two.
1)
    
"FUFUFUF"
Returns: 0.0
The turtle traces a vertical square and ends up where he started.
2)
    
"FRFUF"
Returns: 1.7320508075688772
3)
    
"F(((D)4)4)9F"
Returns: 2.0

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

NextBetter

Search, Sorting



Used in:

TCO07 Semi 2

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

PabloGilberto , vorthys , Cosmin.ro , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6874

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10840&pm=6874

Problem Statement

    String matching is extraordinarily useful. In our application, we define the match quality between 2 strings of lowercase letters to be the number of positions that match exactly. For example, the match quality between "abcdedd" and "bcddd" is 1, since they only match in the 4th character.

We have a string sequence, data, and are interested in finding string sequences of the same length that fit the data well. We say that one sequence fits the data better than another sequence if it has a higher quality match with the data at the first position where the match qualities differ.

String sequences are ordered lexicographically based on the normal alphabetical comparison between individual strings. That means that if position i is the first position where 2 sequences differ, the sequence whose ith element would come later in a dictionary is later in the ordering of sequences. Given data and candidate return the next later permutation of candidate that fits data better. If no lexicographically later permutation of candidate gives a better fit, return candidate.

 

Definition

    
Class:NextBetter
Method:nextPerm
Parameters:String[], String[]
Returns:String[]
Method signature:String[] nextPerm(String[] data, String[] candidate)
(be sure your method is public)
    
 

Constraints

-data will contain between 1 and 50 elements, inclusive.
-candidate will contain the same number of elements as data.
-Each element of data and candidate will contain between 1 and 10 characters, inclusive.
-Each element of data and candidate will contain only lowercase letters ('a'-'z').
 

Examples

0)
    
{"ab","cde"}
{"xx","ade"}
Returns: {"xx", "ade" }
The only permutation of "xx","ade" is earlier (since "ade" precedes "xx"). Therefore, there is no next permutation, and candidate is returned.
1)
    
{"ad","cde"}
{"xx","yde"}
Returns: {"yde", "xx" }
"yde","xx" is the next permutation of "xx","yde" and it fits data better since it has a match quality of 1 in the first position ("yde" vs "ad") while candidate has a match quality of 0 in the first position of data.
2)
    
{"ade","cde","acd"}
{"ab","ae","c"}
Returns: {"ab", "c", "ae" }
All 5 permutations of candidate come later than candidate. "ab","c","ae" fits data better than candidate, and so does "ae","c","ab". None of the other permutations fits data better than candidate. So the return is the earlier of these 2.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GraphBuilder

Graph Theory



Used in:

MM 7

Used as:

Division I Level One

Writer:

lars2520

Testers:

lbackstrom , lb1359

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6858

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10128&pm=6858

Problem Statement

    There are a number of nodes placed at lattice points on a grid. You need to design a network that connects them. You may install new nodes on lattice points, and you may run network cable between any two nodes.



You have two goals in the design of your network. First, you want to minimize the cost of the network you build. That means not installing too many new nodes or running too much cable. Second, you want to make the network fault tolerant. Each node that you install as well as the original nodes, and each unit of cable that you run has some probability of failing.



The inputs x and y will specify the locations of the nodes that must be connected. The input cost will specify how much it will cost if there is a failure that prevents some of the original nodes from communicating. The jth integer in element i of cost will specify the cost incurred if node/cable failures prevents nodes i and j from communicating. The input p represents the probability that a node will fail. The input q respresents the probability that one unit of cable will fail (thus, the probability that a length L cable will fail is 1-(1-q)L). Cable costs 1 per unit length, while nodeCost gives the cost of adding a new node.



Your network design will be judged based on it's expected cost: the sum of the cost of the nodes and cable installed, plus the expected cost resulting from network failures. You should return a String[] where each element specifies either a new node, or a connection between two nodes. If you are installing a new node, the element of the String should specify its coordinates formatted as "x y". If you are installing cable, the element should be formatted as "x1 y1 x2 y2", indicating cable from (x1,y1) to (x2,y2). You may install new nodes in at most 30 unique new locations, and your returned String[] may have at most 1000 elements. If your return is invalid in any way (bad formatting, cables not ending at nodes, etc.), you will be judged as if you returned {} -- you will pay the cost of all communications failing. If you cause a runtime error or exceed the time limit (of 20 seconds) you will also be judged in this way.



The inputs will be randomly generated. All random numbers will be generated uniformly and independently. All ranges are inclusive. First, the number of nodes, N, will be chosen between 5 and 20. Each node will be placed on a unique random lattice point with x and y coordinates between 0 and 99. p and q will be between 0.0 and 0.01. The cost between each pair of nodes will be an integer between 0 and 100,000. nodeCost will be between 10 and 100.



To compute the probability that two nodes can communicate, a monte carlo method will be employed. The random failure process will be simulated 1,000,000 times and the expected cost of the failures will be approximated by the average of these trials.



Your score for each test case will simply be your expected cost as computed by the monte carlo method. Your overall score will simply be 100000 minus the average of your scores on the individual cases. If your score is less than 0, it will be changed to 0.
 

Definition

    
Class:GraphBuilder
Method:build
Parameters:int[], int[], double, double, int, String[]
Returns:String[]
Method signature:String[] build(int[] x, int[] y, double p, double q, int nodeCost, String[] costs)
(be sure your method is public)
    
 

Notes

-You may run multiple cables between the same two nodes.
-You may install multiple nodes at the same lattice point. If you do, they will be connected to each other by default (and of course this connection cannot fail, having length 0). Furthermore, as long as at least one of the multiple nodes at a point does not fail, all cables terminating at that point will be able to communicate through that point. In other words, installing two nodes at a point is equivalent to installing one node at that point that has a probability of failing of p2.
-The original nodes act just like the ones you may add, with the same failure rate as other nodes.
-If one of the original nodes fails, then clearly it will not be able to communicate with any of the other nodes. This is unavoidable, and thus this cost is not counted against you.
-To keep the simulation times down, java.util.Random will be used for random number generation.
-costs will be symmetric and its diagonal entries will be 0.
-The cost of a cable between two points will be the Euclidean distance between those points.
-Cables may cross, and may pass over nodes without being incident to them. For example, a node at (1,1) does not have any effect on a cable from (0,0) to (2,2).
-The memory limit is 64MB.
-Your return should be single-space delimited without leading or trailing spaces.
-The 30 new unique node location limit means that you may create as many nodes as you want in up to 30 new locations. The locations of the nodes given to you do not count against this limit.
 

Examples

0)
    
"1"
Returns: 
"x = {6, 48, 17, 92, 32, 53}
y = {78, 69, 63, 62, 10, 37}
p = 0.004100808114922016
q = 0.0020771484130971706
nodeCost = 17
costs = 
      0 95194 25379 48473 75678 39722
      95194 0 49336 1729 76360 96659
      25379 49336 0 16847 19035 30327
      48473 1729 16847 0 54422 94630
      75678 76360 19035 54422 0 34098
      39722 96659 30327 94630 34098 0 "
One simple strategy would be to place a single node at (50,50) and then connect each of the original nodes to it. However, this is very prone to failure. One way to reduce the risk of failure is to have redundant nodes and edges. If we add two nodes at (50,50), and add 4 cables from every computer to (50,50), we will reduce the risk considerably. Now, there will be a functioning node at (50,50) with probability 1 - p2, and each node will have a functioning cable to (50,50) with pretty high probability.



The cost of the nodes and cables with this strategy is 864.5 and the expected cost from failures is about 74, for a total cost of roughly 939.
1)
    
"2"
Returns: 
"x = {19, 68, 34, 67, 47, 35, 30, 58, 66}
y = {47, 94, 14, 99, 99, 53, 24, 19, 98}
p = 0.009014476240300544
q = 0.004968225934308908
nodeCost = 31
costs = 
      0 91362 16908 94139 90780 74980 58776 68432 12961
      91362 0 42371 69340 73967 41612 75504 1122 79824
      16908 42371 0 26023 8107 78814 9306 60845 44772
      94139 69340 26023 0 62344 4468 34904 40340 52441
      90780 73967 8107 62344 0 2675 7898 86637 70758
      74980 41612 78814 4468 2675 0 56628 65273 94046
      58776 75504 9306 34904 7898 56628 0 54764 11262
      68432 1122 60845 40340 86637 65273 54764 0 91519
      12961 79824 44772 52441 70758 94046 11262 91519 0 "
2)
    
"237787512"
Returns: 
"x = {29, 69, 42, 46, 95, 72, 93, 1, 9}
y = {33, 89, 44, 95, 75, 5, 68, 88, 34}
p = 0.00811194812081668
q = 0.00534613102433974
nodeCost = 19
costs = 
      0 91710 26818 47023 62803 201 26321 43902 69137
      91710 0 27276 25856 1954 77473 63667 90034 93532
      26818 27276 0 75046 33704 90756 13079 32444 61138
      47023 25856 75046 0 82148 12866 98485 86568 83739
      62803 1954 33704 82148 0 44777 75993 38130 11574
      201 77473 90756 12866 44777 0 95959 65328 2423
      26321 63667 13079 98485 75993 95959 0 24480 29330
      43902 90034 32444 86568 38130 65328 24480 0 40488
      69137 93532 61138 83739 11574 2423 29330 40488 0 "
3)
    
"291065735"
Returns: 
"x = {64, 51, 58, 42, 88}
y = {75, 95, 45, 65, 96}
p = 0.0040731303630733165
q = 0.0013070565365267284
nodeCost = 55
costs = 
      0 13927 7998 42420 57221
      13927 0 3176 92108 94332
      7998 3176 0 70383 16346
      42420 92108 70383 0 52311
      57221 94332 16346 52311 0 "
4)
    
"845813853"
Returns: 
"x = {44, 8, 96, 17, 12, 22, 43, 40, 36, 62, 99, 19, 97, 87, 87, 8}
y = {32, 42, 90, 43, 36, 2, 71, 10, 6, 43, 13, 16, 69, 77, 1, 44}
p = 0.0016942263381844326
q = 0.003814951307056981
nodeCost = 91
costs = 
      0 77669 65398 43088 71887 12439 81519 21556 19523 58242 63192 20445 19681 52511 82820 7224
      77669 0 85952 13838 29342 78256 31831 45959 8151 67026 20196 76116 83809 54635 4011 43020
      65398 85952 0 35761 17702 82358 25360 17420 5792 41513 83982 61359 66083 26928 86775 26943
      43088 13838 35761 0 35729 36433 27150 45651 57224 52420 86476 56070 57659 74556 72981 15669
      71887 29342 17702 35729 0 91173 82855 18454 8250 2430 20641 6656 52647 61889 2068 82851
      12439 78256 82358 36433 91173 0 2324 66826 30278 73358 245 73734 9016 25617 29616 23372
      81519 31831 25360 27150 82855 2324 0 17920 13750 55476 75191 79110 26125 25264 76076 13602
      21556 45959 17420 45651 18454 66826 17920 0 31454 48183 29439 38870 85360 31125 40906 68780
      19523 8151 5792 57224 8250 30278 13750 31454 0 98482 56835 58689 34467 70294 16824 18871
      58242 67026 41513 52420 2430 73358 55476 48183 98482 0 71174 3710 95894 16615 75165 20514
      63192 20196 83982 86476 20641 245 75191 29439 56835 71174 0 48763 43067 8333 48449 32499
      20445 76116 61359 56070 6656 73734 79110 38870 58689 3710 48763 0 81429 10294 9957 20285
      19681 83809 66083 57659 52647 9016 26125 85360 34467 95894 43067 81429 0 53857 29478 31645
      52511 54635 26928 74556 61889 25617 25264 31125 70294 16615 8333 10294 53857 0 2518 1973
      82820 4011 86775 72981 2068 29616 76076 40906 16824 75165 48449 9957 29478 2518 0 16617
      7224 43020 26943 15669 82851 23372 13602 68780 18871 20514 32499 20285 31645 1973 16617 0 "
5)
    
"152208291"
Returns: 
"x = {3, 15, 22, 49, 39, 60, 82, 66, 50}
y = {48, 63, 64, 87, 11, 63, 3, 0, 11}
p = 0.008264446916240231
q = 0.007788336306338746
nodeCost = 92
costs = 
      0 77967 51877 27131 80229 31822 74540 46540 12912
      77967 0 66155 16155 8034 35808 22795 60135 11773
      51877 66155 0 56078 90246 77516 35786 64769 85614
      27131 16155 56078 0 49291 93171 69545 4903 86022
      80229 8034 90246 49291 0 40058 43650 40456 82616
      31822 35808 77516 93171 40058 0 16614 25592 33985
      74540 22795 35786 69545 43650 16614 0 60560 18621
      46540 60135 64769 4903 40456 25592 60560 0 51704
      12912 11773 85614 86022 82616 33985 18621 51704 0 "
6)
    
"585537344"
Returns: 
"x = {7, 57, 11, 80, 55, 92}
y = {72, 41, 31, 74, 47, 27}
p = 0.006583582796657616
q = 0.006224951045415638
nodeCost = 96
costs = 
      0 99469 40545 36911 89709 39339
      99469 0 70083 25060 82569 91026
      40545 70083 0 48313 90775 28948
      36911 25060 48313 0 19095 8917
      89709 82569 90775 19095 0 10560
      39339 91026 28948 8917 10560 0 "
7)
    
"193475383"
Returns: 
"x = {75, 66, 2, 91, 30, 67, 66, 7, 43, 74, 72, 33, 2, 57}
y = {27, 28, 93, 98, 22, 44, 80, 85, 97, 69, 46, 26, 91, 57}
p = 0.005119199353456559
q = 0.00233858613264591
nodeCost = 79
costs = 
      0 73318 23837 13038 48840 44716 51384 45139 605 78222 2383 25761 58234 93207
      73318 0 24708 93061 78532 63220 28310 17893 12286 42328 78832 86212 76052 71079
      23837 24708 0 80561 98642 19790 21705 93011 9697 17833 46922 22582 508 82797
      13038 93061 80561 0 9509 84335 91762 51204 84954 53870 4306 34086 35528 12956
      48840 78532 98642 9509 0 15124 90317 14283 64762 90430 80507 90203 95766 53457
      44716 63220 19790 84335 15124 0 41504 54854 2471 12175 14678 78092 9080 44902
      51384 28310 21705 91762 90317 41504 0 14884 28467 52053 81362 810 37463 38426
      45139 17893 93011 51204 14283 54854 14884 0 61643 19029 69225 11994 53928 80220
      605 12286 9697 84954 64762 2471 28467 61643 0 8673 69183 37395 16015 41185
      78222 42328 17833 53870 90430 12175 52053 19029 8673 0 17901 20715 67703 53976
      2383 78832 46922 4306 80507 14678 81362 69225 69183 17901 0 6495 56554 24308
      25761 86212 22582 34086 90203 78092 810 11994 37395 20715 6495 0 41860 64687
      58234 76052 508 35528 95766 9080 37463 53928 16015 67703 56554 41860 0 33033
      93207 71079 82797 12956 53457 44902 38426 80220 41185 53976 24308 64687 33033 0 "
8)
    
"810622701"
Returns: 
"x = {59, 23, 32, 5, 38, 48, 13, 75, 53, 23, 86, 84, 1, 18, 98, 70, 87, 88, 19}
y = {72, 20, 23, 61, 0, 8, 85, 69, 72, 39, 84, 30, 10, 4, 75, 92, 12, 14, 47}
p = 0.00724697587422273
q = 3.594426926882632E-4
nodeCost = 33
costs = 
      0 76020 48775 52436 62850 46095 47662 68187 91453 82801 8970 12962 30917 10106 37961 20056 62292 21270 95897
      76020 0 86067 21391 5614 84665 64134 24348 34702 95666 50482 30637 77441 89051 90787 54627 41232 67377 31079
      48775 86067 0 41241 74226 98781 79751 82602 15650 35707 25502 21453 74002 96942 43165 21290 24956 86115 63628
      52436 21391 41241 0 88338 52168 75847 53303 85202 56379 32395 23044 44457 69283 95190 82928 10532 91660 68295
      62850 5614 74226 88338 0 84058 9930 48040 96374 90608 60713 22399 37078 75985 11315 79268 30410 95581 98603
      46095 84665 98781 52168 84058 0 60896 15736 15828 87583 41779 92443 18468 85657 23163 48104 13422 25329 90558
      47662 64134 79751 75847 9930 60896 0 10727 9094 74371 22272 82033 3294 89505 91943 16788 41995 21340 11509
      68187 24348 82602 53303 48040 15736 10727 0 8592 456 94418 21096 5065 62864 10863 47783 16906 98426 28435
      91453 34702 15650 85202 96374 15828 9094 8592 0 63107 82280 31573 27340 31877 19045 53187 53799 60741 957
      82801 95666 35707 56379 90608 87583 74371 456 63107 0 3885 91855 65689 75931 36036 28946 76106 59341 97765
      8970 50482 25502 32395 60713 41779 22272 94418 82280 3885 0 23210 58146 74625 62642 25771 61349 95272 28346
      12962 30637 21453 23044 22399 92443 82033 21096 31573 91855 23210 0 53240 53844 80656 82869 55348 10227 14790
      30917 77441 74002 44457 37078 18468 3294 5065 27340 65689 58146 53240 0 37344 7988 3042 16894 46929 95645
      10106 89051 96942 69283 75985 85657 89505 62864 31877 75931 74625 53844 37344 0 82015 54558 60990 47323 72894
      37961 90787 43165 95190 11315 23163 91943 10863 19045 36036 62642 80656 7988 82015 0 81404 85568 85386 14113
      20056 54627 21290 82928 79268 48104 16788 47783 53187 28946 25771 82869 3042 54558 81404 0 24853 90567 4630
      62292 41232 24956 10532 30410 13422 41995 16906 53799 76106 61349 55348 16894 60990 85568 24853 0 18497 22310
      21270 67377 86115 91660 95581 25329 21340 98426 60741 59341 95272 10227 46929 47323 85386 90567 18497 0 42999
      95897 31079 63628 68295 98603 90558 11509 28435 957 97765 28346 14790 95645 72894 14113 4630 22310 42999 0 "
9)
    
"173530689"
Returns: 
"x = {98, 13, 32, 71, 81, 57, 33, 71, 2, 62, 33, 36, 60, 25, 0, 39, 74, 63}
y = {46, 50, 98, 99, 10, 53, 52, 56, 69, 97, 66, 31, 67, 71, 18, 56, 70, 74}
p = 0.008420372767857684
q = 0.008580875521429242
nodeCost = 91
costs = 
      0 1938 17938 89667 34256 82565 76861 83631 61892 65080 62667 48473 38836 79925 72355 90465 52833 54901
      1938 0 22624 34739 91459 44177 81269 65812 39621 80560 52651 58100 86157 71183 54465 23620 17618 81501
      17938 22624 0 27863 83372 21630 37387 780 97936 86937 22607 10729 40242 63071 11432 15028 31509 87055
      89667 34739 27863 0 17581 31996 78747 44222 75622 36459 50317 85008 34504 54641 88035 96912 20273 60262
      34256 91459 83372 17581 0 60058 40919 80829 32569 81029 72780 13806 92055 84812 3872 25057 45768 14713
      82565 44177 21630 31996 60058 0 15596 68456 97168 95864 23942 88530 39566 46800 96425 63799 78716 70750
      76861 81269 37387 78747 40919 15596 0 37241 75619 98363 34941 78223 51753 13622 76679 20763 71354 73555
      83631 65812 780 44222 80829 68456 37241 0 61949 92386 83844 30854 73186 93073 9520 12627 33074 83611
      61892 39621 97936 75622 32569 97168 75619 61949 0 63787 16190 70021 61037 38069 47231 36845 75340 59116
      65080 80560 86937 36459 81029 95864 98363 92386 63787 0 84618 4772 94828 77198 34802 77159 76000 86054
      62667 52651 22607 50317 72780 23942 34941 83844 16190 84618 0 60963 96085 29839 34144 70568 68331 50930
      48473 58100 10729 85008 13806 88530 78223 30854 70021 4772 60963 0 47190 96335 36845 3227 7848 79810
      38836 86157 40242 34504 92055 39566 51753 73186 61037 94828 96085 47190 0 33086 88326 94790 59320 56625
      79925 71183 63071 54641 84812 46800 13622 93073 38069 77198 29839 96335 33086 0 75347 34727 73380 20289
      72355 54465 11432 88035 3872 96425 76679 9520 47231 34802 34144 36845 88326 75347 0 33177 47237 83013
      90465 23620 15028 96912 25057 63799 20763 12627 36845 77159 70568 3227 94790 34727 33177 0 69708 31363
      52833 17618 31509 20273 45768 78716 71354 33074 75340 76000 68331 7848 59320 73380 47237 69708 0 73260
      54901 81501 87055 60262 14713 70750 73555 83611 59116 86054 50930 79810 56625 20289 83013 31363 73260 0 "

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MarbleNecklace

Simple Search, Iteration, Sorting, String Manipulation



Used in:

SRM 328

Used as:

Division II Level One

Writer:

_efer_

Testers:

PabloGilberto , brett1479 , Olexiy , lovro

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6855

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10008&pm=6855

Problem Statement

    

Consider a necklace composed of marbles of various colors arranged in a circle. The colors are represented by uppercase letters. We can describe a necklace with a string of characters as follows: start with any marble and go through all the marbles in either a clockwise or counter-clockwise direction, until the starting marble is reached again, meanwhile appending to the string the colors of the marbles in the order they are visited. Obviously, there could be many different strings describing the same necklace. For example, the necklace described by the string "CDAB" can also be described by seven other strings (see example 0).

You are given a String necklace containing the description of a necklace. Return the description for that necklace that comes earliest alphabetically.

 

Definition

    
Class:MarbleNecklace
Method:normalize
Parameters:String
Returns:String
Method signature:String normalize(String necklace)
(be sure your method is public)
    
 

Constraints

-necklace will contain between 1 and 50 characters, inclusive.
-Each character of necklace will be an uppercase letter ('A'-'Z').
 

Examples

0)
    
"CDAB"
Returns: "ABCD"
This necklace can be described by the eight strings "CDAB", "DABC", "ABCD", "BCDA", "CBAD", "DCBA", "ADCB", "BADC". "ABCD" comes first lexicographically.
1)
    
"RGB"
Returns: "BGR"
2)
    
"TOPCODER"
Returns: "CODERTOP"
3)
    
"SONBZELGFEQMSULZCNPJODOWPEWLHJFOEW"
Returns: "BNOSWEOFJHLWEPWODOJPNCZLUSMQEFGLEZ"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BlockEnemy

Dynamic Programming, Graph Theory, Greedy, Search, String Parsing



Used in:

SRM 328

Used as:

Division I Level Two

Writer:

_efer_

Testers:

PabloGilberto , brett1479 , Olexiy , lovro

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6852

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10008&pm=6852

Problem Statement

    

You ran into some trouble when playing your favorite video game. There are N towns on the map, numbered from 0 to N-1. For each pair of distinct towns, there is exactly one way to get from one to the other by following one or more roads. Your enemy has just occupied some of the towns, and your first attempt at blocking him is to remove some of the roads in order to block off communication between every pair of distinct occupied towns. You would like to do this with as little effort as possible.

You will be given a String[] roads describing the roads between towns. Each element of roads is in the form "a b e" (quotes for clarity only), meaning that there is a bidirectional road between towns a and b, and the effort required to destroy the road is e. You will also be given a int[] occupiedTowns containing the towns occupied by your enemy. Return the minimum total effort required to destroy enough roads so that no two distinct occupied towns have a path (direct or indirect) between them.

 

Definition

    
Class:BlockEnemy
Method:minEffort
Parameters:int, String[], int[]
Returns:int
Method signature:int minEffort(int N, String[] roads, int[] occupiedTowns)
(be sure your method is public)
    
 

Constraints

-N will be between 2 and 50, inclusive.
-roads will contain between 1 and 50 elements, inclusive.
-Each element of roads will contain between 5 and 50 characters, inclusive.
-Each element of roads will be in the form "a b e" (quotes for clarity) where a and b are distinct integers between 0 and N-1, inclusive, and e is an integer between 1 and 1,000,000, inclusive.
-The integers in roads will not contain extra leading zeroes.
-There will be exactly one way to get from one town to any other, by following one or more roads.
-occupiedTowns will contain between 1 and 50 elements, inclusive.
-Each element of occupiedTowns will be between 0 and N-1, inclusive.
-The elements of occupiedTowns will be distinct.
 

Examples

0)
    
5
{"1 0 1", "1 2 2", "0 3 3", "4 0 4"}
{3, 2, 4}
Returns: 4
To make the communication between town 2 and the other occupied towns impossible, we must destroy one of the first two roads. We choose the first one as it requires less effort. Similarly, we choose between the last two roads in order to disconnect towns 3 and 4. The total cost is therefore 4.
1)
    
5
{"1 0 1", "1 2 2", "0 3 3", "4 0 4"}
{3}
Returns: 0
This is the same map as above. Since there is only one occupied town, we don't need to destroy any road here.
2)
    
12
{"0 1 3", "2 0 5", "1 3 1", "1 4 8", "1 5 4", "2 6 2",
 "4 7 11", "4 8 10", "6 9 7", "6 10 9", "6 11 6"}
{1, 2, 6, 8}
Returns: 13
Towns 1 and 2 are on the path from 6 to 8. We have to destroy the sixth road to disconnect town 6 from 2. We must destroy one of the first two roads to disconnect towns 1 and 2 and we pick the first one. Also, we should destroy one of the roads on the path from 1 to 8 and we choose the fourth road. The total cost is 2 + 3 + 8 = 13.
3)
    
12
{"0 1 3", "2 0 5", "1 3 1", "1 4 8", "1 5 4", "2 6 2",
 "4 7 11", "4 8 10", "6 9 7", "6 10 9", "6 11 6"}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
Returns: 66
We have to destroy all roads this time.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PostfixRLE

Dynamic Programming, Encryption/Compression, Graph Theory, String Parsing



Used in:

SRM 327

Used as:

Division I Level Three

Writer:

Petr

Testers:

PabloGilberto , brett1479 , Olexiy , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6834

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10007&pm=6834

Problem Statement

    

Postfix notation (or reverse Polish notation) is a method for writing down arithmetic expressions without brackets, but still maintaining the order of operations. The postfix notation for an expression consisting of a single variable or number consists only of that variable or number. The postfix notation for an expression "A#B" (here A and B are other expressions and '#' is the operator evaluated last in our expression) is obtained by concatenating the postfix notation for A, the postfix notation for B, and '#'.

For example, the postfix notation for "((a+f)*b)*(c*d)" is "af+b*cd**". Another way of looking at the postfix notation is that it is a program for a stack calculator. Every variable or number means "push that variable or number on the stack". Every operator means "pop the two top items from the stack, perform the operation on them, and push the result back on the stack". For example, when evaluating "af+b*cd**", the stack changes as follows: {a}, {a,f}, {a+f}, {a+f,b}, {(a+f)*b}, {(a+f)*b,c}, {(a+f)*b,c,d}, {(a+f)*b,c*d}, {((a+f)*b)*(c*d)}.

You are given an expression in postfix notation, containing only variables and operators. All the operators are binary (take two operands), associative, and commutative. That means for any operator #, expressions A, B, and C, the following properties hold:

  • Associativity: A#(B#C)=(A#B)#C.
  • Commutativity: A#B=B#A.

That allows you to rearrange operands corresponding to the same operator. For example, using both rules one could rearrange the expression shown above:

  • As expression: "((a+f)*b)*(c*d)" can be rearranged to "d*((a+f)*(b*c))".
  • In postfix notation: "af+b*cd**" can be rearranged to "daf+bc***".

Your task is to find a postfix expression that can be obtained by rearranging the initial expression using only the associativity and commutativity rules, and having the least RLE-size. The RLE-size of a string is the number of blocks of consecutive equal characters in it (i.e., the RLE-size of "xx+yy+zz+**" is 7).

The input for this problem is given as a String[] expression. Concatenate all elements of that String[] to get the initial expression in postfix notation. Each variable is denoted by a lowercase letter ('a'-'z'), and the operators are denoted by characters '+', '*', '#', '!', '@', '$', '%' and '^'. You are to return the smallest possible RLE-size of a postfix expression that can be obtained from the initial expression by applying some (possibly none) of the above rules.

 

Definition

    
Class:PostfixRLE
Method:getCompressedSize
Parameters:String[]
Returns:int
Method signature:int getCompressedSize(String[] expression)
(be sure your method is public)
    
 

Notes

-All the quotes in the problem statement are for clarity only.
 

Constraints

-expression will contain between 1 and 50 elements, inclusive.
-Each element of expression will contain between 1 and 50 characters, inclusive.
-Each character in each element of expression will be a lowercase letter ('a'-'z'), '+', '*', '#', '!', '@', '$', '%' or '^'.
-expression will be a valid arithmetic expression in postfix notation.
 

Examples

0)
    
{"af+b*cd**"}
Returns: 7
"daf+bc***" is one of the possible best rearrangements.
1)
    
{"xy*x*y*x*y*"}
Returns: 3
Yields "xxxyyy*****" or "yyyxxx*****".
2)
    
{"abcdefg!@#$%^"}
Returns: 13
No point in changing anything here.
3)
    
{"xy@z@ab@c@yc%%%"}
Returns: 9
4)
    
{"abc++",
"abc++",
"abc++",
"a",
"b",
"c",
"*",
"*",
"*",
"*",
"*"}
Returns: 13

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BuffetLine

Dynamic Programming



Used in:

TCCC06 Finals

Used as:

Division I Level Three

Writer:

legakis

Testers:

PabloGilberto , brett1479 , Yarin , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6830

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10136&pm=6830

Problem Statement

    

Before the final round of the TCCC, audience members head to the buffet for lunch. The buffet line contains a number of food items, in a fixed order. Those indulging line up at the buffet, each intending to sample a subset of the items available.

It takes each person exactly 10 seconds to help themselves to a food item. Every 10 seconds, each person moves up as far as they can (without passing by any food they want, of course!). This movement takes no time. The first person in line moves immediately to each item he wants, in order, spending 10 seconds at each item. Depending on which items the rest of the people want, they may be able to move up to each item immediately, but also may have to spend some time waiting for the person they are following.

Each person is always either waiting in line before reaching the first food item, standing in front of exactly one food item, or has passed the last food item and is looking for a place to sit. Two people may not stand in front of the same food item at the same time. Also, people always remain in the order in which they lined up, and they never move backward in line. No one ever passes another person in line -- even after they have taken all the food they want, they still exit the buffet in line. People can only take a food item that they are standing directly in front of. Anyone who cannot reach the next food item they want (because they are waiting for the person in front of them) will advance as far as possible in line, to avoid blocking the people behind them unnecessarily.

Anxious to get back to the TCCC event, the people wish to get the group through the buffet line as quickly as possible. Given the list of food items in the buffet and the items that each person wants, return the optimal order in which the people should line up at the buffet so that everyone can get all the food they desire in the least total amount of time.

The food items available at the buffet will be given as a String food. Each item in food will contain only letters ('a'-'z', 'A'-'Z'), and there will be exactly one space between each pair of adjacent items. Each item in food will be unique. The order of items in food is the order they appear in the buffet line, with the first item in food being the first item available. The items each person wants are given in a String[] cravings. There will be one element in cravings for each person. Each element in cravings will be a list of food items found in food, with exactly one space between each food items. Within each element of cravings, each food item will be unique.

Return a int[] containing the optimal order, where each element is the 0-based index of a person in cravings, and elements are ordered from first to last in line. If there are multiple solutions, return the one that comes first lexicographically. A int[] a1 comes before a int[] a2 lexicographically if, at the first element at which they differ, a1 contains the smaller value.

 

Definition

    
Class:BuffetLine
Method:order
Parameters:String, String[]
Returns:int[]
Method signature:int[] order(String food, String[] cravings)
(be sure your method is public)
    
 

Constraints

-food will contain between 1 and 50 characters, inclusive.
-food will be formatted as described in the problem statement and contain between 1 and 8 items, inclusive.
-food will not contain any duplicate items.
-cravings will contain between 1 and 12 elements, inclusive.
-Each element of cravings will contain between 0 and 50 characters, inclusive.
-Each element of cravings will be formatted as described in the problem statement.
-Each word in each element of cravings will be an item from food.
-Each element of cravings will not contain any duplicate items.
 

Examples

0)
    
"applesauce beans carrots dates eggplant"
{ "beans",
  "applesauce",
  "dates" }
Returns: {2, 0, 1 }
All three people can get through the line in 10 seconds if the person who wants dates goes first, followed by the person who wants beans, and then the person who wants applesauce. Any other order would require 20 or 30 seconds.
1)
    
"applesauce beans carrots dates eggplant"
{ "beans",
  "applesauce",
  "beans",
  "dates" }
Returns: {0, 1, 3, 2 }
In this example there are two people who want beans. Since only one person can take any given food item at once, it will take at least 20 seconds for all 4 people to get through the line. There are several orders that get them through in 20 seconds, and { 0, 1, 3, 2 } is selected according to the tiebreaking rules.
2)
    
"bread water"
{ "" }
Returns: {0 }
3)
    
"A B C D E F"
{ "A C E D",
  "A B D E F",
  "B C A D",
  "B C F D E",
  "B D C F" }
Returns: {3, 1, 0, 4, 2 }
4)
    
"A B C"
{ "A", "A", "A", "A",
  "B", "B", "B", "B",
  "C", "C", "C", "C" }
Returns: {8, 4, 0, 9, 5, 1, 10, 6, 2, 11, 7, 3 }
5)
    
"A G E F D B H C"
{ "D C A H",
  "H B F G A",
  "B F G D",
  "F C E B A G",
  "D H B C",
  "B A D F G",
  "E B C F D",
  "A D H E B G",
  "A H B G E C",
  "F D A B C",
  "B D A G C",
  "A G E C F" }
Returns: {0, 4, 1, 10, 9, 6, 2, 3, 11, 8, 7, 5 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LicensePlate

Greedy, String Parsing



Used in:

TCHS SRM 31

Used as:

Division I Level Three

Writer:

connect4

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6823

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10655&pm=6823

Problem Statement

    

Almost every different government in the world has a different method of assigning license plates to vehicles. In any of these systems, it is possible to take all possible plates, arrange them in lexicographical order, and number them, where the first plate is 0, the second plate is 1, etc. Your local government has decided to do this with the license plates that it issues, and right before you leave to eat lunch, you have been assigned this daunting project. So that you can actually have a warm meal today, you have decided to write a program to do this for you.

You will be given a String format, containing the format of the local license plates. Each character of format will be either an uppercase letter ('A'-'Z'), a number ('0'-'9'), a space (' '), a dash ('-'), or the lowercase letters 'u', 'n', or 'a'. If the character is a 'u', it means that any uppercase letter can be used in that place. If the character is an 'n', it means that any number can be used in that place. If the character is an 'a', it means that any uppercase letter or number can be used in that place. If the character is not a lowercase letter, then the character in that spot must be the one used in format. For instance, if the format was "AB-una", then "AB-C52" and "AB-D3G" would be legal license plates, but "AC-D3G", "AB-111", and "AB-DEF" would not.

Given the format, you are to return the n-th earliest (0-indexed) license plate that can be formed in this system. If the n-th license plate cannot be formed using the given format, return an empty String. Note that numbers occur earlier lexicographically than letters (e.g., '4' comes before 'B').

 

Definition

    
Class:LicensePlate
Method:getPlate
Parameters:String, int
Returns:String
Method signature:String getPlate(String format, int n)
(be sure your method is public)
    
 

Constraints

-format will contain between 1 and 50 characters, inclusive.
-Each character of format will be an uppercase letter ('A'-'Z'), a number ('0'-'9'), a space (' '), a hyphen ('-'), or the lowercase letters 'a', 'n', or 'u'.
-n will be between 0 and 2^31-1, inclusive.
 

Examples

0)
    
"ABu"
2
Returns: "ABC"
The license plates in this format are "ABA", "ABB", "ABC", "ABD", etc. We return the 2nd (0-based) element in this list, which is "ABC".
1)
    
"ABn"
2
Returns: "AB2"
2)
    
"ABa"
12
Returns: "ABC"
Remember that numbers come first in lexicographical order.
3)
    
"A BC"
2
Returns: ""
There are only 1 possible license plate in this format ("ABC"), so we must return a blank plate.
4)
    
"una"
8732
Returns: "Y2K"
5)
    
"ABa  DEuF-GHuJ KL-aMNaa5390u"
1345876
Returns: "AB0  DEAF-GHBJ KL-3MNXW5390M"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AlmostBipartiteMatching

Graph Theory



Used in:

TCCC06 Wildcard

Used as:

Division I Level One

Writer:

soul-net

Testers:

PabloGilberto , brett1479 , Olexiy , Jan_Kuipers

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6820

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10135&pm=6820

Problem Statement

    

The maximum matching of a graph is the largest possible set of edges in which no two edges share a common vertex.

Bipartite graphs are graphs whose nodes can be divided into two sets A and B such that each edge in the graph has one endpoint in A and one endpoint in B. In these graphs, the maximum matching problem can be perfectly solved in polynomial time using maximum flow algorithms.

In this problem you will be given a graph that is almost bipartite and you will have to calculate the maximum matching of that graph. An almost bipartite graph is a graph whose nodes can be divided into two sets A = {a0,...,anA-1} and B = {b0,...,bnB-1} such that all edges have one endpoint in A and one endpoint in B with the exception of the edges from ai to ai+1 that exist for every i between 0 and nA-2, inclusive, and the edges from bi to bi+1 that allways exist for every i between 0 and nB-2, inclusive.

You will be given nA and nB as two ints. The set of edges that have one endpoint in A and one endpoint in B is given as two int[]s edgesA and edgesB. The ith edge has one endpoint aedgesA[ i ] and one endpoint bedgesB[ i ]. Since they are always part of the graph, edges with two endpoints in the same set are implicit. Return the size of the maximum set of edges in this graph that do not share a vertex.

 

Definition

    
Class:AlmostBipartiteMatching
Method:maxMatching
Parameters:int, int, int[], int[]
Returns:int
Method signature:int maxMatching(int nA, int nB, int[] edgesA, int[] edgesB)
(be sure your method is public)
    
 

Constraints

-nA and nB will each be between 1 and 1000, inclusive.
-edgesA will contain between 0 and 50 elements, inclusive.
-edgesA and edgesB will contain the same number of elements.
-Each element of edgesA will be between 0 and nA-1, inclusive.
-Each element of edgesB will be between 0 and nB-1, inclusive.
 

Examples

0)
    
3
3
{0,1,2}
{0,1,2}
Returns: 3
A perfect matching can be achieved by using all the edges with one endpoint in each set. There are other ways to get the same result.
1)
    
3
3
{0,1}
{1,2}
Returns: 2
2)
    
6
6
{0,0,2,3}
{2,4,5,1}
Returns: 6
3)
    
13
16
{5,2,6,2,7,2,7,6,2,6,1,3,0,10,12,11,10}
{7,3,10,12,0,0,3,4,7,2,5,2,14,15,1,1,1}
Returns: 14

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ExtendedDominoes

Graph Theory, Math



Used in:

SRM 322

Used as:

Division I Level Two

Writer:

soul-net

Testers:

PabloGilberto , brett1479 , Olexiy , Mike Mirzayanov

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6779

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10002&pm=6779

Problem Statement

    

This problem statement contains superscripts that may not display correctly in some plugins. If that's the case, use the arena to see them.

You have recently bought a game of extended dominoes. Each domino is a rectangle partitioned into two squares, and each square contains a number between 0 and 9, inclusive. There are exactly 45 pieces - one for each pair of distinct numbers. Pieces may be reversed, so while there is only one piece containing the numbers 1 and 2, it can be used in either of the following ways:

   +---+---+     +---+---+
   | 1 | 2 |     | 2 | 1 |
   +---+---+     +---+---+

Unfortunately, some of the pieces have disappeared, but there is still a possible game left: How many ways are there to construct a cycle collection with all the remaining pieces?

A cycle collection is a set of 1 or more cycles that do not share pieces. A cycle is constructed by ordering and orienting the pieces in such a way that the left number of the piece in position i is equal to the right number of the piece in position i-1, and the left number of the piece in the first position is equal to the right number of the piece in the last position (positions are numbered from left to right).

   +---+---++---+---++---+---++---+---++---+---++---+---+
   | 1 | 2 || 2 | 5 || 5 | 4 || 4 | 2 || 2 | 8 || 8 | 1 |   
   +---+---++---+---++---+---++---+---++---+---++---+---+

   +---+---++---+---++---+---++---+---++---+---++---+---+
   | 1 | 2 || 2 | 4 || 4 | 5 || 5 | 2 || 2 | 8 || 8 | 1 |   
   +---+---++---+---++---+---++---+---++---+---++---+---+

   +---+---++---+---++---+---+  +---+---++---+---++---+---+
   | 1 | 2 || 2 | 8 || 8 | 1 |  | 4 | 5 || 5 | 2 || 2 | 4 |   
   +---+---++---+---++---+---+  +---+---++---+---++---+---+

The figure above shows three possible cycle collections that use the same set of pieces. We say that each piece is connected to the two pieces that surround it, and the first and last pieces are also connected. Two cycles are considered the same if each piece is connected to the same two other pieces in both cycles. Two cycle collections are the same if they contain the same set of cycles.

You will be given the existing pieces as a String[] pieces, where each element contains exactly two digits representing the two numbers on a single domino. Return the number of distinct cycle collections that can be formed with these pieces.

 

Definition

    
Class:ExtendedDominoes
Method:countCycles
Parameters:String[]
Returns:long
Method signature:long countCycles(String[] pieces)
(be sure your method is public)
    
 

Notes

-Remember that each cycle collection must use all the pieces, and no two cycles in a collection can share pieces.
 

Constraints

-pieces will contain between 1 and 45 elements, inclusive.
-Each element of pieces will contain exactly 2 characters.
-Each character of each element of pieces will be a digit ('0'-'9').
-In each element of pieces the value of its first character will be less than the value of its second character.
-No two elements of pieces will be equal.
-The number of cycles for pieces will be less than 263.
 

Examples

0)
    
{"12","25","45","24","28","18"}
Returns: 3
The example in the problem statement.
1)
    
{"01","12","23","34","45"}
Returns: 0
There is no way to form a cycle here.
2)
    
{"09","12","24","14","57","79","05"}
Returns: 1
The only possibility is:
   +---+---++---+---++---+---++---+---+  +---+---++---+---++---+---+
   | 0 | 9 || 9 | 7 || 7 | 5 || 5 | 0 |  | 1 | 2 || 2 | 4 || 4 | 1 |   
   +---+---++---+---++---+---++---+---+  +---+---++---+---++---+---+
3)
    
{"34","35","36","37","45","46","47","56","57","67"}
Returns: 243

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BikeRiding

Dynamic Programming, Graph Theory



Used in:

SRM 345

Used as:

Division II Level Three

Writer:

rusolis

Testers:

PabloGilberto , brett1479 , Olexiy , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6763

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10669&pm=6763

Problem Statement

    

Your friend likes riding his bike on the hills outside your town. He asked you to help him count the number of routes he can take. There are several locations on the hills, some of them directly connected by paths (you can take each path only in one given direction). He would like to start at one of the locations given in startPoints and end at location endPoint. Return the number of distinct routes that he can use to do that. If the number is larger than n or infinite, return -1.

The definition of a route is as follows:

  • A legal route is a sequence of locations starting with one from startPoints and ending with endPoint. Each location on the route other than the last one has a path leading to the next consecutive location.
  • Two routes are distinct if they each have a different sequence of locations.
  • A route can have any length.
  • Any location (including endPoint) may be present multiple times on the route.

You are given all locations and connections between them in the String[] paths. The j-th character of the i-th element of paths is '1' (one) if there is a direct one-way path from location i to location j, and '0' (zero) otherwise.

 

Definition

    
Class:BikeRiding
Method:countRoutes
Parameters:String[], int[], int, int
Returns:int
Method signature:int countRoutes(String[] paths, int[] startPoints, int endPoint, int n)
(be sure your method is public)
    
 

Constraints

-paths will contain between 2 and 50 elements, inclusive (let k be this number).
-Each element of paths will contain exactly k characters.
-Each element of paths will contain only '0' (zero) and '1' (one) characters.
-endPoint and each element of startPoints will be between 0 and k-1.
-Each element in startPoints will be distinct.
-None of the elements in startPoints will be equal to endPoint
-n will be between 2 and 10^9, inclusive.
 

Examples

0)
    
{"011" ,"001", "000"}
{0,1}
2
5
Returns: 3
There is one possible route from location 1, and two from location 0.
1)
    
{"01000",
 "00100",
 "00010",
 "01001",
 "00000"}
{0}
4
10
Returns: -1
The number of routes is infinite.
2)
    
{"000111000000000","000111000000000","000111000000000",
 "000000111000000","000000111000000","000000111000000",
 "000000000111000","000000000111000","000000000111000",
 "000000000000111","000000000000111","000000000000111",
 "000000000000001","000000000000001","000000000000000"}
{0,1,2}
14
1000
Returns: 243
3)
    
{"010", "100", "001"}
{0}
2
10
Returns: 0
There is no possible route.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MatrixPainting

Graph Theory



Used in:

TCCC06 Round 2C

Used as:

Division I Level Two

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Cosmin.ro , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6760

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10113&pm=6760

Problem Statement

    

There is a matrix with 9 rows and 9 columns. Each cell of the matrix is either black or white. With a single repaint operation, you can repaint all the cells in a single row or column black if the row or column already contains at least 5 black cells. Your goal is to make all the cells in the matrix black using a minimal number of repaint operations.

You will be given a String[] matrix, where the jth character of the ith element represents the cell at row i, column j. Black cells will be written as '1' (one), and white cells will be written as '0' (zero). Return the minimal number of repaint operations required to make all the cells black, or -1 if this is impossible.

 

Definition

    
Class:MatrixPainting
Method:countRepaints
Parameters:String[]
Returns:int
Method signature:int countRepaints(String[] matrix)
(be sure your method is public)
    
 

Constraints

-matrix will contain exactly 9 elements.
-Each element of matrix will contain exactly 9 characters.
-Each element of matrix will consist of '0' and '1' characters only.
 

Examples

0)
    
{"001111111",
 "011111111",
 "011111111",
 "011111111",
 "011111111",
 "101111111",
 "101111111",
 "101111111",
 "101111111"}
Returns: 3
First, you should repaint the first row. After that, you can repaint the first and the second column.
1)
    
{"011111111",
 "101111111",
 "110111111",
 "111011111",
 "111101111",
 "111110111",
 "111111011",
 "111111101",
 "111111110"}
Returns: 9
Each white cell must be repainted separately.
2)
    
{"000000001",
 "000000011",
 "000000111",
 "000001111",
 "000011111",
 "000011110",
 "000011100",
 "000011000",
 "000010000"}
Returns: 14
After repainting the 5 rightmost columns, you will be able to repaint the rows.
3)
    
{"000000001",
 "000000011",
 "000000111",
 "000001111",
 "000011111",
 "000011110",
 "000011100",
 "000011000",
 "000000000"}
Returns: -1
4)
    
{"011111111",
 "010001001",
 "111111101",
 "011111111",
 "101010100",
 "011111111",
 "111111101",
 "111011101",
 "011111111"}
Returns: 5

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MergingGraph

Dynamic Programming, Graph Theory



Used in:

SRM 321

Used as:

Division I Level Three

Writer:

Mike Mirzayanov

Testers:

PabloGilberto , brett1479 , Olexiy , lovro

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6758

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10001&pm=6758

Problem Statement

    

You are given a directed graph. The graph may contain loops, and multiple edges may exist between pairs of vertices. You can merge a pair of vertices into a single vertex. When a pair of vertices is merged, outgoing and incoming edges from both vertices become outgoing and incoming edges, respectively, of the resulting vertex. For example, consider a graph with four vertices {a, b, c, d} and three edges {a->b, c->b, c->d}. If we merge vertices b and c, the resulting graph will have three vertices {a, bc, d} and three edges {a->bc, bc->bc, bc->d}.

A graph is a cycle if its vertices can be ordered v0, v1, ..., vn-1 (where n is the total number of vertices) such that the following two properties are satisfied:

  • Every edge in the graph goes from vi to v(i+1)%n.
  • For all i between 0 and n-1, inclusive, there exists at least one edge that goes from vi to v(i+1)%n.

You are given a String[] adj. The ith element of adj is a space delimited list of integers representing all the outgoing edges from vertex i. Each integer represents the target vertex of an outgoing edge. Return the minimal number of merge operations necessary to convert the given graph into a cycle. If a solution doesn't exist, return the number of vertices in the given graph instead.

 

Definition

    
Class:MergingGraph
Method:distanceToCycle
Parameters:String[]
Returns:int
Method signature:int distanceToCycle(String[] adj)
(be sure your method is public)
    
 

Constraints

-adj will contain between 1 and 50 elements, inclusive.
-Each element of adj will contain between 0 and 50 characters, inclusive.
-Each element of adj will be a single space separated list of integers.
-Each number in each element of adj will be between 0 and (n - 1) inclusive, where n is the number of elements in adj.
-Each number in each element of adj will contain no leading zeroes.
 

Examples

0)
    
{"1 1", "2", "0 0 0"}
Returns: 0
This graph is already a cycle.
1)
    
{"0 1 1", "2", "0 0 0"}
Returns: 2
The resulting cycle is a loop.
2)
    
{"1", "", "3", ""}
Returns: 2
The resulting cycle has 2 vertices.
3)
    
{"2", "5 4", "", "0", "0", "0 0"}
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WeirdSort

Sorting



Used in:

SRM 321

Used as:

Division I Level Two

Writer:

Mike Mirzayanov

Testers:

PabloGilberto , brett1479 , Olexiy , lovro

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6755

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10001&pm=6755

Problem Statement

    You are given a int[] data, and you must order the elements of data such that no two consecutive elements have consecutive values. In other words, result[i] + 1 != result[i + 1] for all i, where 0 <= i < n-1, and n is the number of elements in data. If more than one ordering exists, return the one that comes first lexicographically.
 

Definition

    
Class:WeirdSort
Method:sortArray
Parameters:int[]
Returns:int[]
Method signature:int[] sortArray(int[] data)
(be sure your method is public)
    
 

Constraints

-data will contain between 1 and 50 elements, inclusive.
-Each element of data will be between 0 and 1000, inclusive.
 

Examples

0)
    
{1, 2}
Returns: {2, 1 }
Only one possible ordering exists.
1)
    
{1, 2, 3}
Returns: {1, 3, 2 }
There are only three possible orderings: {1, 3, 2}, {2, 1, 3} and {3, 2, 1}. The first one is lexicographically smallest.
2)
    
{1, 1, 1, 1, 2, 2, 2, 2, 2}
Returns: {2, 2, 2, 2, 2, 1, 1, 1, 1 }
All 2's should be before 1's.
3)
    
{1, 2, 3, 4, 5, 6}
Returns: {1, 3, 2, 4, 6, 5 }
4)
    
{1, 1, 2, 2, 3, 3}
Returns: {1, 1, 3, 3, 2, 2 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Problem Statement

    

You have just been hired by a cartography company, and your first task is to help them with a map they are trying to make. The owner of the company thinks it should always be possible to color a map using only four colors (such that no touching states have the same color), but so far they have been unable to do so with the map of Familyland. This is quite important to him, as he can print maps using four colors of ink for only $0.00001 per square millimeter. Each additional ink, however, has a base cost of $N/100 and a usage cost of $N/100000 per square millimeter (where N is the number of the ink, so N=5 is the first ink that is more expensive).

The company will be printing 100mm x 100mm maps of Familyland, so you can see that the costs will add up quickly if many additional inks are needed. If the map can be made with only 4 inks, it will cost only $0.10 each to make, but if a 5th ink were needed, even on only 1 square millimeter of the map, the cost would rise to $0.15004 (note that you still only pay $0.00001/mm^2 for the first four inks).

The problem with this particular map is that the country of Familyland has a representative government, but the citizens would not put up with anyone but a family member being their representative. To deal with this, Familyland declared each family to be its own state. Since not all family members live next to one another, the states are not contiguous. Of course, in making the map, each state must be entirely one color.

If you want to keep your new job, you will need to come up with a coloring of the map such that it can be printed as cheaply as possible. Your score on each test case will be the cost in dollars of printing the map using the coloring you return. Your total score (the one displayed in the division summary) will be the sum over all testcases of the lowest cost anyone has achieved for the case divided by your cost for the case. In the unlikely event of a true tie (as computed using high precision numerics), the competitor with the lowest total runtime on all cases will be declared the winner.

You will be given the area of each state (in square millimeters in map scale), and an adjacency matrix where character i of string j is '1' if states i and j are adjacent and '0' if they are not. Character i of string i will always be '0'. You must return an ink color for each state such that no two adjacent states have the same color. In the event that your returned coloring is invalid (you return a different number of colors than there are states, or you color two adjacent states the same), or your program exceeds the 30 second time limit, you will receive a 0 on the case.

The test cases will be generated as follows (unless otherwise stated, all random choices are uniform and independent and ranges are inclusive):

  1. The number of states (S) will be randomly chosen between 10 and 500.
  2. The number of properties will be randomly chosen between S and 4*S.
  3. For the first S properties, a random x and y will be chosen between 0 and 99 (assuring that no two properties are at the same location). The pixel at the x and y coordinate on the 100x100 map is marked as belonging to the ith state.
  4. Each remaining property is placed on the map in the same manner, except that a random state between 0 and S-1 is assigned to the x and y coordinate on the map.
  5. The remaining map pixels are assigned to states by randomly picking an unassigned map pixel that borders an assigned pixel, randomly choosing one of the assigned pixels that borders it, and assigning that pixel's state to the unassigned pixel. This process continues until the map is filled.
  6. The adjacency matrix and the array of state areas are constructed from this map.
 

Definition

    
Class:MapMaker
Method:colorStates
Parameters:int[], String[]
Returns:int[]
Method signature:int[] colorStates(int[] area, String[] adj)
(be sure your method is public)
    
 

Notes

-The time limit for each test case is 30 seconds.
-There are 50 non-example test cases.
-The memory limit is 1GB, and the thread limit is 32.
-There will be between 10 and 500 states inclusive. (chosen uniformly)
-Returned colors must all be >= 1.
-To facilitate testing, the values of S and P were not chosen randomly for example cases 0 through 3.
 

Examples

0)
    
"-1"
Returns: 
"</pre>10 states, 10 properties<br>
<br>
Areas:<br>
1477, 538, 1429, 1106, 381, 685, 1605, 224, 1807, 748   <br><br>
Adjacency Matrix:<br>
<pre style='font-size:8px;'>0000011010
0000000111
0000101000
0000011000
0010001101
1001001000
1011110011
0100100001
1100001001
0100101110
</pre>"
Here is an image of the generated map that was used to construct the adjacency matrix and calculate the areas:

1)
    
"-2"
Returns: 
"</pre>10 states, 20 properties<br>
<br>
Areas:<br>
1403, 777, 954, 2302, 918, 2217, 495, 282, 91, 561   <br><br>
Adjacency Matrix:<br>
<pre style='font-size:8px;'>0111111001
1011110001
1101100000
1110110100
1111010010
1101101111
1000010101
0001011000
0000110000
1100011000
</pre>"
Here is an image of the generated map that was used to construct the adjacency matrix and calculate the areas:

2)
    
"-3"
Returns: 
"</pre>10 states, 40 properties<br>
<br>
Areas:<br>
845, 1484, 725, 755, 620, 369, 1084, 619, 1238, 2261   <br><br>
Adjacency Matrix:<br>
<pre style='font-size:8px;'>0111100111
1001111111
1001000111
1110011111
1100011011
0101101001
0101110111
1111001011
1111101101
1111111110
</pre>"
Here is an image of the generated map that was used to construct the adjacency matrix and calculate the areas:

3)
    
"-4"
Returns: 
"</pre>500 states, 2000 properties<br>
<br>
Areas:<br>
3, 29, 51, 18, 48, 14, 20, 21, 37, 14, 15, 24, 34, 17, 16,<br>
9, 11, 17, 27, 27, 1, 27, 39, 31, 4, 20, 9, 24, 12, 11,<br>
31, 9, 43, 5, 34, 11, 38, 25, 30, 11, 20, 17, 32, 35, 25,<br>
13, 3, 18, 17, 26, 38, 7, 46, 17, 13, 4, 11, 17, 6, 1,<br>
11, 28, 23, 13, 31, 23, 31, 11, 11, 39, 17, 21, 43, 12, 44,<br>
23, 12, 31, 10, 21, 31, 17, 35, 9, 8, 29, 4, 22, 28, 9,<br>
25, 25, 38, 20, 20, 4, 35, 9, 20, 16, 17, 14, 24, 10, 8,<br>
22, 7, 20, 23, 19, 13, 19, 28, 15, 16, 15, 19, 11, 32, 8,<br>
11, 10, 32, 40, 27, 6, 22, 31, 16, 14, 17, 14, 17, 18, 19,<br>
12, 21, 11, 13, 10, 14, 38, 24, 20, 27, 21, 24, 55, 20, 13,<br>
18, 24, 35, 35, 27, 8, 24, 10, 17, 22, 29, 13, 10, 10, 10,<br>
43, 12, 18, 11, 14, 10, 9, 24, 29, 14, 20, 31, 30, 3, 15,<br>
15, 19, 5, 20, 4, 47, 15, 26, 30, 23, 30, 18, 44, 20, 13,<br>
11, 26, 23, 21, 10, 23, 16, 14, 13, 24, 17, 9, 27, 20, 46,<br>
20, 10, 15, 14, 14, 14, 7, 40, 21, 39, 58, 8, 22, 11, 28,<br>
11, 32, 34, 10, 30, 6, 25, 19, 33, 3, 19, 32, 23, 35, 5,<br>
19, 14, 11, 24, 26, 36, 19, 18, 20, 17, 24, 23, 19, 9, 34,<br>
12, 29, 5, 18, 41, 38, 17, 34, 29, 19, 22, 25, 7, 47, 19,<br>
6, 10, 5, 10, 17, 18, 24, 4, 15, 24, 19, 3, 19, 4, 15,<br>
11, 13, 13, 15, 28, 16, 8, 20, 12, 13, 34, 8, 6, 22, 16,<br>
35, 9, 26, 30, 16, 39, 19, 9, 42, 36, 16, 40, 15, 8, 27,<br>
6, 21, 18, 20, 20, 14, 24, 15, 17, 25, 9, 11, 13, 23, 17,<br>
45, 4, 8, 12, 62, 10, 15, 44, 9, 33, 25, 38, 22, 21, 20,<br>
30, 12, 21, 6, 34, 10, 19, 43, 14, 16, 33, 17, 5, 18, 5,<br>
27, 16, 34, 38, 21, 11, 6, 7, 40, 5, 11, 30, 25, 21, 30,<br>
29, 32, 27, 4, 22, 9, 10, 7, 1, 12, 24, 28, 35, 13, 30,<br>
19, 5, 28, 22, 16, 17, 18, 27, 9, 21, 22, 2, 13, 5, 47,<br>
16, 17, 23, 29, 17, 23, 8, 2, 13, 29, 18, 13, 11, 33, 8,<br>
11, 24, 23, 19, 13, 13, 19, 33, 40, 17, 32, 19, 18, 29, 7,<br>
21, 30, 14, 12, 12, 21, 17, 14, 8, 14, 15, 33, 13, 12, 45,<br>
19, 12, 14, 8, 14, 8, 23, 54, 13, 22, 26, 46, 8, 23, 9,<br>
17, 12, 15, 23, 16, 28, 33, 18, 14, 30, 44, 2, 30, 27, 14,<br>
12, 33, 13, 41, 8, 10, 21, 9, 15, 38, 8, 22, 13, 4, 14,<br>
36, 12, 33, 30, 7   "
Download adjacency matrix
4)
    
"2081178672"
Returns: 
"</pre>358 states, 1000 properties<br>
<br>
Areas:<br>
15, 50, 15, 15, 57, 52, 19, 28, 10, 31, 15, 26, 47, 45, 40,<br>
15, 9, 15, 33, 95, 19, 60, 24, 12, 32, 9, 49, 33, 31, 25,<br>
5, 1, 51, 54, 35, 46, 38, 30, 19, 78, 113, 29, 31, 25, 42,<br>
11, 12, 21, 16, 14, 48, 33, 15, 12, 16, 11, 25, 18, 4, 36,<br>
30, 127, 31, 43, 32, 28, 38, 31, 11, 48, 17, 14, 60, 37, 14,<br>
40, 13, 31, 48, 19, 13, 12, 13, 23, 35, 21, 17, 16, 15, 19,<br>
14, 33, 20, 29, 40, 64, 55, 4, 17, 21, 28, 29, 11, 77, 63,<br>
15, 5, 13, 1, 50, 24, 52, 42, 21, 16, 31, 23, 25, 28, 17,<br>
26, 38, 4, 23, 12, 27, 30, 29, 28, 7, 2, 21, 28, 26, 15,<br>
15, 77, 8, 5, 67, 18, 43, 25, 35, 10, 37, 16, 52, 16, 34,<br>
9, 14, 33, 41, 6, 32, 37, 44, 14, 14, 73, 20, 55, 27, 19,<br>
45, 45, 43, 28, 18, 23, 13, 13, 30, 46, 11, 11, 3, 5, 18,<br>
25, 79, 21, 8, 14, 48, 19, 36, 18, 14, 4, 25, 10, 39, 7,<br>
32, 33, 15, 16, 15, 11, 26, 9, 14, 21, 46, 9, 30, 37, 19,<br>
15, 19, 15, 26, 48, 18, 33, 37, 32, 12, 7, 53, 20, 20, 7,<br>
41, 18, 23, 30, 25, 14, 31, 14, 17, 13, 25, 21, 62, 40, 25,<br>
8, 38, 22, 13, 59, 16, 26, 49, 3, 13, 17, 16, 23, 22, 34,<br>
24, 10, 19, 50, 35, 29, 5, 6, 59, 9, 52, 13, 7, 41, 35,<br>
12, 23, 77, 34, 20, 4, 31, 29, 25, 26, 13, 54, 66, 36, 29,<br>
47, 26, 56, 25, 51, 30, 29, 1, 56, 37, 34, 28, 24, 21, 20,<br>
12, 40, 13, 8, 3, 10, 3, 36, 18, 29, 47, 26, 29, 52, 38,<br>
10, 13, 4, 46, 25, 41, 22, 8, 16, 30, 35, 50, 10, 17, 37,<br>
25, 14, 41, 23, 21, 36, 44, 63, 54, 9, 28, 29, 52, 6, 28,<br>
25, 17, 36, 30, 57, 21, 107, 31, 20, 47, 30, 9, 48   "
Download adjacency matrix
5)
    
"1607679183"
Returns: 
"</pre>232 states, 784 properties<br>
<br>
Areas:<br>
90, 40, 9, 97, 42, 94, 25, 16, 21, 43, 73, 44, 25, 77, 67,<br>
60, 79, 43, 50, 9, 18, 24, 7, 60, 69, 7, 106, 63, 39, 46,<br>
50, 82, 42, 33, 15, 53, 63, 98, 78, 59, 51, 14, 56, 110, 59,<br>
37, 33, 53, 93, 48, 18, 25, 61, 11, 143, 42, 33, 24, 63, 5,<br>
67, 3, 99, 107, 16, 33, 71, 11, 6, 32, 24, 37, 60, 9, 71,<br>
51, 28, 34, 2, 79, 44, 36, 51, 3, 42, 44, 102, 22, 127, 14,<br>
26, 29, 15, 79, 15, 62, 20, 17, 39, 28, 21, 31, 54, 49, 7,<br>
17, 41, 14, 22, 28, 39, 31, 41, 33, 62, 88, 30, 55, 80, 8,<br>
59, 45, 22, 52, 49, 22, 25, 31, 51, 17, 61, 10, 73, 15, 38,<br>
33, 62, 55, 21, 103, 1, 20, 20, 52, 66, 62, 36, 14, 91, 20,<br>
129, 74, 22, 50, 72, 21, 31, 22, 30, 15, 47, 31, 19, 71, 63,<br>
41, 50, 19, 52, 44, 13, 46, 32, 57, 60, 14, 70, 23, 33, 15,<br>
48, 26, 8, 47, 23, 74, 61, 102, 15, 31, 6, 13, 10, 8, 71,<br>
95, 34, 45, 47, 75, 64, 5, 33, 35, 20, 24, 9, 28, 68, 50,<br>
37, 14, 37, 33, 51, 71, 11, 86, 68, 14, 56, 51, 13, 26, 38,<br>
65, 24, 57, 73, 61, 44, 2   "
Download adjacency matrix
6)
    
"1046542405"
Returns: 
"</pre>420 states, 1393 properties<br>
<br>
Areas:<br>
23, 9, 33, 32, 43, 24, 12, 18, 22, 31, 17, 14, 11, 48, 24,<br>
26, 10, 22, 33, 17, 6, 25, 28, 30, 24, 26, 63, 71, 43, 17,<br>
50, 15, 22, 46, 6, 15, 16, 34, 13, 20, 12, 3, 22, 15, 47,<br>
39, 29, 42, 30, 40, 19, 42, 19, 30, 36, 27, 2, 29, 44, 22,<br>
13, 8, 24, 30, 37, 19, 52, 14, 15, 33, 7, 22, 25, 30, 35,<br>
13, 3, 30, 33, 32, 11, 31, 25, 38, 45, 10, 12, 45, 25, 14,<br>
41, 17, 16, 28, 16, 64, 27, 30, 17, 8, 19, 9, 1, 61, 14,<br>
4, 8, 15, 24, 6, 38, 26, 14, 4, 16, 22, 15, 20, 16, 2,<br>
14, 12, 1, 6, 8, 8, 25, 37, 8, 18, 52, 8, 21, 40, 31,<br>
4, 16, 16, 17, 17, 29, 18, 9, 18, 7, 18, 33, 69, 20, 38,<br>
15, 8, 47, 22, 36, 18, 30, 4, 16, 18, 19, 21, 19, 25, 22,<br>
29, 7, 26, 3, 18, 31, 27, 29, 32, 45, 45, 21, 37, 10, 37,<br>
17, 10, 25, 25, 15, 7, 9, 23, 11, 45, 8, 18, 9, 8, 46,<br>
21, 20, 47, 30, 10, 20, 8, 7, 12, 18, 26, 25, 21, 18, 25,<br>
27, 35, 24, 15, 12, 32, 4, 14, 19, 11, 31, 12, 28, 22, 22,<br>
36, 20, 64, 14, 10, 14, 23, 5, 31, 10, 16, 28, 19, 35, 29,<br>
4, 47, 29, 1, 18, 13, 18, 34, 45, 6, 56, 41, 30, 14, 47,<br>
23, 13, 12, 16, 20, 25, 29, 12, 69, 18, 11, 5, 41, 9, 32,<br>
7, 37, 34, 6, 16, 7, 15, 44, 15, 7, 54, 20, 22, 33, 33,<br>
22, 27, 25, 13, 22, 6, 33, 17, 12, 31, 33, 26, 13, 13, 13,<br>
24, 7, 36, 19, 7, 63, 43, 32, 1, 13, 25, 19, 16, 33, 53,<br>
27, 39, 9, 12, 45, 13, 23, 21, 10, 48, 4, 51, 19, 36, 19,<br>
34, 9, 18, 30, 14, 36, 51, 10, 15, 35, 22, 19, 29, 38, 25,<br>
22, 23, 13, 66, 20, 30, 8, 14, 9, 47, 36, 11, 16, 5, 22,<br>
19, 25, 12, 55, 26, 74, 53, 36, 26, 17, 19, 46, 47, 3, 4,<br>
39, 9, 24, 25, 12, 21, 30, 29, 56, 18, 20, 38, 5, 25, 45,<br>
39, 24, 26, 63, 33, 34, 36, 3, 19, 27, 2, 23, 18, 43, 33,<br>
24, 13, 5, 18, 56, 24, 30, 32, 8, 27, 16, 15, 10, 24, 31   "
Download adjacency matrix
7)
    
"52994217"
Returns: 
"</pre>92 states, 286 properties<br>
<br>
Areas:<br>
100, 165, 136, 65, 94, 95, 35, 48, 2, 104, 108, 128, 160, 58, 52,<br>
64, 231, 107, 52, 166, 114, 69, 93, 59, 123, 211, 91, 215, 73, 200,<br>
438, 193, 136, 31, 58, 64, 77, 76, 86, 98, 42, 47, 132, 152, 66,<br>
92, 101, 40, 118, 64, 53, 76, 142, 118, 89, 113, 94, 89, 136, 39,<br>
224, 83, 162, 67, 182, 65, 129, 155, 175, 127, 59, 107, 42, 68, 72,<br>
293, 44, 14, 151, 83, 200, 35, 14, 101, 242, 77, 75, 142, 70, 120,<br>
83, 261   <br><br>
Adjacency Matrix:<br>
<pre style='font-size:8px;'>00000000000000000010001000000000100000100000000000001100000000110000001000000000000000000010
00000000000000001100011000000111000001100000100011000000001000101000001000010000000110000000
00010001000000000000000010000010100000000010000000000001010010010010000100010000000000001001
00100000000000001000000010000010000000000000000000010100000000001000000000010000000000000001
00000000001001000100101000000010000000000000000000000000000000101000000000000000010000001001
00000000000000000000000000110000000000000010000100001010000000000000100000000010000000000110
00000000000100000001000000000000000000000000001000000000000000010000000000010000000010000001
00100000000000001000001010100001000100000000000000000001000000000000000100010000000000000001
00000000000000000000000000000000000000000000000000000000000000000000000000000010000000010000
00000000000000001011100101000001011000000010001000010100000100000000000000100010000000010100
00001000000001101000010010000000000000000001010001001100100110000100000100000010010000010101
00000010000011010001000000001010000000000101001000000000101010001010000000000000000000000001
00000000000101100001000001010011000000000000000010000001100000000001000100000000100001100000
00001000001110000000000000000010000000000000010010001000000000100000000000000000000000000001
00000000001010000000000000010010000000000001000000000001100000000000000100000000000000000000
00000000000100000000000000000100010000000000000000000000000001000010000000010100000100000001
01010001011000000001001010000010110100000000000011010111000000100000111000010000101010100111
01001000000000000010000000000010000000001000000001000000001011001000000000010000000010000010
10000000010000000100000000010001000000001000000000000000100000000100001000000010000000000010
00000010010110001000000000010100100000000001000000000000011010010000000000010010000010010010
00001000010000000000001001010010000000010010000000000000001111000000000000000010000000000000
01000000001000000000000100000100000000100000001000000100000100000100000000000000000000010001
11001001000000001000100001000011100001000000000000001011001000100001010000000000000000000001
00000000010000000000010001000000001100100010001000010000000000000000000000000000000000000000
00110001001000001000000000100011100000000010010001000000000010000000110100000001000000000001
00000000010010000000101100010000100100000010111000011010001010100001000100000000101010010000
00000101000000000000000010010001000100000000000101100000000010000000000011010000000000100000
00000100000010100011100001100011000000100011000000000010101001000001000000000010000010110000
00000000000100000000000000000000000000000000000000001000000010100010000000000000100001100101
01000000000000010001010000000000000000000000000010000010000010001010100100000001100000100001
01111000000111101100101010010001000000111111000110011111110010001001101110100011100110001000
01000001010010000010001010110010100001000011100010001101101000000000001011010010000100100011
10100000000000001001001011000001000000100000000000000000000000110000001001010010000010000011
00000000010000011000000000000000000000000000000010000000000000000000000000010010000001000000
00000000010000000000000100000000000100000010001000001000000110000000000000000000000010000100
00000001000000001000000101100000001000000000000001000000000000000000000000000000100000000100
00000000000000000000000000000000000000010000000010100110000000000100000000000011000000000000
01000000000000000000001000000001000000000000010000000001000000000010111000001001000000000001
11000000000000000000010100010010100000000010100000000110001000000011011100000000000000110000
00000000000000000000100000000010000010000010000110100000000000000000000001010000000000000001
00000000000000000110000000000010000000000010000000000000000000000100000000000000000000000000
00000000000100000000000000000010000000000011000000000000000001001000000000000000000010000000
00100100010000000000100111010011001000111101000100000100000000000110001100000011000010001010
00000000001100100001000000010011000000000110010000000000100000001001000000010010000100000000
01000000000000000000000001000001000000100000000000000000001000001000010000000000000100010000
00000000001001000000000011000000000001000001000000000000100000000001100000001000100110000101
00000010010100000000010101000000001000000000000000000000001010010000000000000000001010100001
00000100000000000000000000100010000000010010000000000000000000000000000010000000000000001010
01000000000011001000000000000111010010010000000000001001100000101000101000000000000001000101
01000000001000001100000010100000000100000000000000000000000000000000000000000000000000000001
00000000000000000000000000100000000010010000000000000000000010001100000001000000000000000000
00010000010000001000000101000010000000000000000000001100010000000100000000000000000010010000
10000100001001000000001001001011001000000000000010010010000010100100010000010011000011000110
10010000011000001000010000000011000010100010000000010000100000001100101101100001000000010000
00000100000000001000001001010110000010100000000000001000000000000000100000010011000001100000
00100001000010101000001000000011000001000000000010000000000000000000000000010000100000000001
00000000001110100010000000010011000000000001010010000100000000100100101100000010000011100101
00100000000000000001000000000010000000000000000000010000000000000000000000010000000010000000
01000000000100000101101001010001000000100000101000000000000010000001000000000000000000000000
00000000011000000000110000000000001000000000000000000000000010000100000000000000000000010000
00100000001100000101100011101110001000000000001000101000001100011110000100000000110000110001
00000000000000010100100000010000000000000100000000000000000000001001000000000000000110001000
11001000000001001000001001001000100000000000000010001000100000000001000010010010100010001000
10100010000000000001000000000000100000000000001000000000000010000000000000000000000000000000
01011000000100000100000000000110000000000101100010100100000011000100010000000000110100000010
00000000001000000010010000000000000010001010000000111100100110001000010000000000000000010011
00100000000100010000000000001100000001100010000000000000000010000000100100000100100000000001
00000000000010000000001001010010000000100001010000000000001001100000001000010000100000001000
00000100000000001000000010000110000001000000010010000110100000000010010000000000000000000100
00000000000000001000001010000000000001100000100000001000000000001100101000000001000000010010
11000000000000001010000000000011100001100010000010000100100000000001010100001000000011000010
00100001001010100000000011000110000000100010000000000100100010000010001000000000000011100101
00000000000000000000000000100011000000000000000100000000000000100000000000000000000010001000
00000000000000000000000000100001100000010000000000100100000000000000000000110010000000000000
00000000010000000000000000000010000000000000000000000100000000000000000001000010000100010000
01110011000000011101000000100001110000010001000000001011010000100001000001000000000011000101
00000000000000000000000000000000000001000000010000000000000000000000001000000001000000000000
00000000000000010000000000000000000000000000000000000000000000000010000000000000100100000000
00000100111000000011100000010011110010000011000000001010100000100000000001100000000001010101
00000000000000000000000010000110000011000010000000001110000000000000010000001000100000000000
00000000000010001000000001001110000100000000010000000001000010101011000000000101000101000100
00001000001000000000000000000000000000000000000000000000000010001000000000000000000000000000
00000000000000001000000001000000000000000000001000000000000000000000000000000000000000100000
01000000000000010000000000000011000000000001110000000000000001001000000000100100100000010000
01000010000000001101000001010010101000000110011000011000110001100000001110010000000000001010
00000000000010000000000000001000010000000000000010001010100000000000001100010010100000100100
00000000000010001000000000111101000000100000001000000010100010000000000100000000001001000101
00000000111000000001010001010000000000100000100000010100000110000100010000100010000100000000
00101000000000000000000000000010000000000010000100000000000001100001000010000000000010000010
00000100011000001000000000001000001100000000010010001000100000000000100100010010100001100001
10000100000000001111000000000001100000000010000100001000000000001100011000000000000010001000
00111011001101011000011010001101100001010000011011000001100010000110000100010010000000100100
</pre>"
8)
    
"1078607582"
Returns: 
"</pre>207 states, 439 properties<br>
<br>
Areas:<br>
28, 71, 9, 73, 52, 145, 42, 42, 9, 51, 38, 8, 21, 44, 51,<br>
75, 77, 21, 64, 107, 51, 121, 53, 25, 42, 94, 38, 2, 11, 22,<br>
33, 44, 1, 22, 31, 60, 26, 79, 19, 51, 27, 60, 106, 98, 5,<br>
27, 33, 45, 95, 95, 58, 50, 29, 19, 16, 8, 48, 42, 32, 52,<br>
50, 41, 64, 57, 69, 46, 80, 59, 51, 26, 13, 128, 30, 7, 106,<br>
29, 20, 11, 32, 7, 81, 15, 20, 119, 31, 35, 199, 9, 16, 81,<br>
65, 16, 54, 42, 30, 82, 65, 95, 84, 38, 35, 52, 22, 24, 35,<br>
97, 44, 8, 76, 84, 23, 27, 33, 52, 56, 102, 58, 58, 41, 53,<br>
56, 24, 39, 29, 87, 51, 38, 25, 4, 64, 107, 50, 1, 54, 26,<br>
23, 17, 66, 69, 6, 27, 54, 25, 48, 24, 80, 36, 27, 74, 47,<br>
21, 26, 118, 70, 55, 76, 50, 62, 49, 56, 29, 160, 24, 50, 54,<br>
29, 32, 108, 64, 21, 49, 39, 137, 11, 28, 25, 74, 3, 44, 41,<br>
33, 68, 37, 83, 15, 69, 82, 108, 27, 5, 74, 55, 16, 14, 29,<br>
52, 33, 14, 74, 29, 26, 66, 9, 66, 70, 81, 1   "
Download adjacency matrix
9)
    
"806371075"
Returns: 
"</pre>67 states, 202 properties<br>
<br>
Areas:<br>
144, 231, 413, 64, 167, 193, 39, 160, 244, 333, 55, 67, 315, 108, 134,<br>
305, 163, 67, 5, 148, 105, 54, 196, 77, 234, 84, 78, 227, 280, 255,<br>
103, 101, 346, 120, 109, 146, 50, 153, 111, 35, 30, 209, 112, 174, 262,<br>
84, 174, 137, 128, 163, 85, 79, 88, 17, 39, 174, 247, 167, 270, 187,<br>
108, 69, 159, 234, 281, 87, 17   <br><br>
Adjacency Matrix:<br>
<pre style='font-size:8px;'>0001000010010000000000001100001100011101100100100000000010010101100
0000000100001100100010001011000011000000000011000000101010100011000
0001010111001100000101010001100010000110011010101101001001000001010
1010000001000000000000001000000000000000011010000010100010100000000
0000000011000000000010001001111011000000100000001010000110010000000
0010000100000000100000000000100000000000001010001110000001000010110
0000000010001000000110000000100010000000101000000001000001000000000
0110010010001000100000100000000010000000000000100000001001100000010
1010101101000001000010001000111001010100010011011000000110000100101
0011100010010011000001001000010010011101010000101010000101100001100
0000000000000010100000100000010000000000000000000000000000010000000
1000000001000001100000000100000000000110000000000000000000000001000
0110001100000101010111101001100011010000110011001000000110111000000
0110000000001001000000110010000000000000010010000000000000000000000
0000000001100000000000000000010010000000000100100100000000110011000
0000000011011100010011110001100010000101001010000000100110000001000
0100010100110000000000100000010010000000000000000000001100001001100
0000000000001001000100000000100010010000100000000000100000000000000
0000000000000000000000000010000000100000000000000000000000000000000
0010001000001000010001000000000010000000001000101111000001010000000
0100101010001001000000001000100000000000100000000000100000000011100
0010000001001001000100000000000000011000000000100001000000000000010
0000000100101101100000000000000010100100010000010000000110111101000
0010000000000101000000000000000100000100001000000101000001000010000
1101100011001000000010000101100001000000000011000000000001100000100
1000000000010000000000001000001000000010000000000000000000100000000
0100000000000100001000000001100000100010010001000100000000001011000
0110100000001001000000001010001011000010010010000000000100000001000
0010111010001001010010001010000001000010010011000000100000110000101
0000100011100010100000000000000100100000010000000000000000100010100
1000100010000000000000000101000000000000001100000010000010100000000
1000000000000000000000010000010000000000100000000010000001000010100
0110101101001011110100100001000000010000001000111011000001111010110
0100100010001000000000001001100000000010000010110000000011000000000
0000000000000000001000100010010000000100010000000000000000001010000
1000000011001000010001000000000010001100100010110000100100000001001
1000000001000000000001000000000000010101000000000000000000000000000
1010000011010001000000110000000000111000000001010100000000011000011
0010000000010000000000000111100001000000000000000000000000100001000
1000000001000001000000000000000000001000000000000000000000000100000
1000101000001000010010000000000100010000000000000010100000010000000
0011000011001100000000100011110000100000000011010000001110110000000
0011011000000001000100010000001010000000000000000010000011100100000
1000000000000010000000000000001000000000000000000000000110000111010
0111010010001101000000001001100001010000010001000000100101100001000
0100000010001000000000001010100000000100010010000000000100100000001
1010000101000010000101000000000011010000000000011100000001100001000
0000000010000000000000100000000011010100010000101000000110011100010
0010110011001000000100000000000010000000000000110110000010000000000
0010010000000010000100010010000000000100000000101000000000001010000
0001110001000000000100000000001110000000101000001000000001100000000
0010001000000000000101010000000010000000000000000000010001000000100
0101000000000001010010000000100000010000100010000000000010100000100
0000000000000000000000000000000000000000000000000001000000000010000
0110000100000000100000000000000000000000010000000000000100000000000
0000100011001001100000100001000000010000010111010000001010010001000
1101100010001001000000100000001001000000011100011000100100100100000
0010011101000000000100011000000111000000001010100011000000100000010
0101000101001010000000101100111010000010011011100010100011000000100
1000100000101010000100100000100010000100110000010000000100001001100
0000000000001000100000100010000010100100000000010100000000010000000
1000000010000000000000100000000000000001001100010000000010000001000
0100010000000010000010010010010110100000000100000100010000000000010
1110000001010011100010100011000000010010000110100000000100010100000
1000010011000000100010001000110110000000000000000001100000110000000
0010010100000000000001000000000010000100000100010000000001000010000
0000000010000000000000000000100000010100000001000000000000000000000
</pre>"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

QueenCovering

Brute Force



Used in:

TCCC06 Round 1C

Used as:

Division I Level Two

Writer:

Cosmin.ro

Testers:

PabloGilberto , brett1479 , Olexiy , Andrew_Lazarev

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6723

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10104&pm=6723

Problem Statement

    You are given an 8 x 8 chessboard, and you must place the minimum possible number of queens onto the board such that all cells are under attack from at least one queen, and no queens attack each other. Some of the cells on the board are destroyed. A queen cannot be placed on a destroyed cell, and destroyed cells don't need to be under attack. A queen attacks a cell if it is in the same row, same column, or same diagonal as that cell (even if there are destroyed cells between them). Rows are labelled from 1 to 8 and columns from 'A' to 'H'.

You are given a String[] board, where the jth character of the ith element represents the cell at row i, column j. A '.' denotes an empty cell, and a '#' denotes a destroyed cell. A solution is represented by a string which concatenates the positions of the queens. Each queen will be represented by two characters rc, where r is the row label and c is the column label. For example, if the solution contains one queen at row 1, column H and another at row 5, column C, it can be represented as "1H5C" or "5C1H". If there are several solutions which use the minimal number of queens, return the one that comes first lexicographically.

 

Definition

    
Class:QueenCovering
Method:getPlacement
Parameters:String[]
Returns:String
Method signature:String getPlacement(String[] board)
(be sure your method is public)
    
 

Constraints

-board will have exactly 8 elements.
-Each element of board will contain exactly 8 characters.
-Each character of board will be either '.' or '#'.
 

Examples

0)
    
{
  "........",
  "..######",
  ".#.#####",
  ".##.####",
  ".###.###",
  ".####.##",
  ".#####.#",
  "........"}
Returns: "1A8B"
We place one queen on the first row and the first column, and another queen on the last row and on the second column.
1)
    
{
 "#......#",
 ".#......",
 "..#...#.",
 "........",
 "..#.....",
 "..#..#..",
 "#.......",
 "#...###."}
Returns: "1B2D3A4C5E"
2)
    
{
 "........",
 "........",
 "........",
 "........",
 "........",
 "........",
 "........",
 "........"}
Returns: "1A2C3E4B5D"
3)
    
{
  "..##.##.",
  ".###..##",
  "##..###.",
  "#..#...#",
  ".#.##.#.",
  "#...##..",
  "#..#####",
  "..#..#.#"}
Returns: "1A4C5H6B"
4)
    
{
  "########",
  "########",
  "########",
  "########",
  "########",
  "########",
  "########",
  "########"
}
Returns: ""

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FriendsTrouble

Graph Theory



Used in:

TCHS SRM 14

Used as:

Division I Level Two

Writer:

slex

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6721

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10066&pm=6721

Problem Statement

    

You are given a list of people, and you must divide them into as many groups as possible. Each person must belong to exactly one group, and each group must contain one or more people. Friends must not be split apart, so if two people are friends, they must be in the same group.

You will be given a String[] names, each element of which is the name of a single person. You will also be given a String[] friends, each element of which is formatted as "<name1> <name2>" (quotes for clarity only), meaning that <name1> and <name2> are friends. Each <name1> and <name2> will exist in names. Return the maximum number of groups that can be formed.

 

Definition

    
Class:FriendsTrouble
Method:divide
Parameters:String[], String[]
Returns:int
Method signature:int divide(String[] names, String[] friends)
(be sure your method is public)
    
 

Constraints

-names will contain between 1 and 50 elements, inclusive.
-Each element of names will contain between 1 and 20 uppercase letters ('A'-'Z'), inclusive.
-All elements in names will be distinct.
-friends will contain between 0 and 50 elements, inclusive.
-Each element of friends will be formatted as "<name1> <name2>" (quotes for clarity only), where both <name1> and <name2> are elements of names.
 

Examples

0)
    
{"BOB", "HARRY", "ALICE", "SALLY"}
{"BOB ALICE", "HARRY SALLY"}
Returns: 2
BOB and ALICE form one group, and HARRY and SALLY form a second group. The only other valid division is putting them all in a single group, but we want to maximize the number of groups
1)
    
{"BOB", "HARRY", "ALICE", "SALLY"}
{"BOB HARRY", "HARRY ALICE", "ALICE SALLY" }
Returns: 1
There is no way to form more than one group without separating a pair of friends.
2)
    
{"CHUCK"}
{"CHUCK CHUCK","CHUCK CHUCK","CHUCK CHUCK"}
Returns: 1
CHUCK is his own only friend. Note that friends may have duplicate entries.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Linez

Graph Theory, Math, Search



Used in:

MM 5

Used as:

Division I Level One

Writer:

wz

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6686

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10101&pm=6686

Problem Statement

    

Linez is a single-player board game played on a 9x9 grid. On each turn, the player must move one of the numbers on the board to an empty cell where a clear path (consisting of horizontally connected or vertically connected empty cells) exists between the new position and the old. If five or more same numbers are aligned in a row, column, or diagonal, they will be removed from the board. The player will gain 10+k*(k-5)/2 points (k being the number of removals) and can make another move. Otherwise, three more numbers will be placed onto the board at randomly chosen positions before the player can move again. The objective is to score as many points as possible before the whole board fills up. (An online version of the Linez game is available at http://linez.varten.net/.)

Your task is to write a class to play the Linez game. The method nextMove will be given the board configuration and the next three numbers. board will contain 9 Strings representing the rows of the board from top to bottom. Each element will contain 9 characters. Each character will be '1' to '7' representing the number on that cell, or '.' if that position is unoccupied. nextThree will contain 3 characters. Each element of nextThree will be '1' to '7' representing the number to be added to the board next turn. The return value of nextMove must contain 4 characters, the first two representing the original position of the number to be moved, the next two representing the target position. For example, to move the number "4" from "I8" to "F6" as shown below, return "I8F6".

You will have a total of 20 seconds for each test case. The memory limit is 64MB. Your final score will be the mean score on all the test cases.

 

Definition

    
Class:Linez
Method:nextMove
Parameters:String[], String
Returns:String
Method signature:String nextMove(String[] board, String nextThree)
(be sure your method is public)
    
 

Notes

-Each number of nextThree will be chosen uniformly between 1 and 7, inclusive.
-Each empty cell has an equal probability to be chosen when the next number is added to the board.
-If your solution crashes, runs out of time, or tries to make an invalid move it will receive the points it has made so far for that test case.
 

Examples

0)
    
"149738788"
Returns: 
"board:<br>{<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.....4...&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;......5..&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;......3..&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;<br>}<br>nextThree:<br>&nbsp;&nbsp;&quot;545&quot;<br>"
1)
    
"1982697456"
Returns: 
"board:<br>{<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.......5.&quot;,<br>&nbsp;&nbsp;&quot;3........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;....7....&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;<br>}<br>nextThree:<br>&nbsp;&nbsp;&quot;773&quot;<br>"
2)
    
"2060431272"
Returns: 
"board:<br>{<br>&nbsp;&nbsp;&quot;..6.....4&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;...1.....&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;<br>}<br>nextThree:<br>&nbsp;&nbsp;&quot;154&quot;<br>"
3)
    
"1077274560"
Returns: 
"board:<br>{<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;7........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;..6....2.&quot;<br>}<br>nextThree:<br>&nbsp;&nbsp;&quot;563&quot;<br>"
4)
    
"825809896"
Returns: 
"board:<br>{<br>&nbsp;&nbsp;&quot;.6.......&quot;,<br>&nbsp;&nbsp;&quot;.....6...&quot;,<br>&nbsp;&nbsp;&quot;.4.......&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;<br>}<br>nextThree:<br>&nbsp;&nbsp;&quot;745&quot;<br>"
5)
    
"1911009"
Returns: 
"board:<br>{<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.6.4.....&quot;,<br>&nbsp;&nbsp;&quot;........6&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;<br>}<br>nextThree:<br>&nbsp;&nbsp;&quot;151&quot;<br>"
6)
    
"149738789"
Returns: 
"board:<br>{<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;......3..&quot;,<br>&nbsp;&nbsp;&quot;..3......&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;..2......&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;<br>}<br>nextThree:<br>&nbsp;&nbsp;&quot;455&quot;<br>"
7)
    
"1109944003"
Returns: 
"board:<br>{<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.....1...&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.6.......&quot;,<br>&nbsp;&nbsp;&quot;......5..&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;<br>}<br>nextThree:<br>&nbsp;&nbsp;&quot;527&quot;<br>"
8)
    
"1732993602"
Returns: 
"board:<br>{<br>&nbsp;&nbsp;&quot;.2.......&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;...6.....&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.......1.&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;<br>}<br>nextThree:<br>&nbsp;&nbsp;&quot;564&quot;<br>"
9)
    
"1438702088"
Returns: 
"board:<br>{<br>&nbsp;&nbsp;&quot;........2&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.....2...&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;,<br>&nbsp;&nbsp;&quot;....5....&quot;,<br>&nbsp;&nbsp;&quot;.........&quot;<br>}<br>nextThree:<br>&nbsp;&nbsp;&quot;624&quot;<br>"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DominoesLines

Graph Theory



Used in:

TCCC06 Round 2A

Used as:

Division I Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , radeye , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6679

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10110&pm=6679

Problem Statement

    

Dominoes is a game played with rectangular tiles. Each tile (domino) is split in half vertically and contains two numbers between 0 and 6, inclusive. One tile A can be played after tile B if the left number of A is the same as the right number of B. Several consecutively played tiles are called a line. For example, the picture below shows a line containing four tiles.

You will be given a String[] tiles. Each element of tiles will be in the format "X:Y" where X and Y are digits between 0 and 6, inclusive. You should arrange these tiles into as few lines as possible. You can turn over any tile, i.e., the tile "2:5" can also be used as "5:2". Each tile should be used exactly once. Your method should return the constructed lines as a String[]. Each element should represent a single line, formatted as a dash-separated list of tiles in the order and orientation they occur in the line. If there is more than one solution possible, return the solution whose first element comes first lexicographically. If there are still multiple solutions, return the one among them whose second element comes first lexicographically, and so on.

 

Definition

    
Class:DominoesLines
Method:constructLines
Parameters:String[]
Returns:String[]
Method signature:String[] constructLines(String[] tiles)
(be sure your method is public)
    
 

Constraints

-tiles will contain between 1 and 50 elements, inclusive.
-Each element of tiles will be in the format "X:Y" where X and Y are digits between 0 and 6, inclusive.
 

Examples

0)
    
{"1:0", "1:1", "1:2", "1:3", "1:4"}
Returns: {"0:1-1:1-1:2", "3:1-1:4" }
1)
    
{"4:0", "4:1", "4:2", "4:3", "4:4"}
Returns: {"0:4-4:1", "2:4-4:4-4:3" }
2)
    
{"0:0", "1:1", "2:2", "3:3", "6:6", "6:0"}
Returns: {"0:0-0:6-6:6", "1:1", "2:2", "3:3" }
3)
    
{"0:4", "6:6", "1:2", "1:1", "3:1", "4:4", "0:1", "1:5", "5:0"}
Returns: {"0:1-1:1-1:2", "3:1-1:5-5:0-0:4-4:4", "6:6" }
4)
    
{"3:1", "0:2", "6:1", "6:3", "4:6", "6:4", 
 "2:3", "4:0", "5:2", "2:2", "6:6"}
Returns: {"2:0-0:4", "3:1-1:6-6:4-4:6-6:6-6:3-3:2-2:2-2:5" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PenPuzzle

Graph Theory



Used in:

TCCC06 Qual 1

Used as:

Division I Level Three

Writer:

Olexiy

Testers:

PabloGilberto , brett1479 , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6667

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10093&pm=6667

Problem Statement

    

PenPuzzle is a variation on the famous Rubik's cube. Imagine a polygonal cylinder with k sides, where each side is divided into m slots (for a total of k*m slots). All slots are of the same height, so the slots form several levels (the lowermost slots on each side form one level, the slots directly above those form another level, and so on). Each slot contains a single colored plate. There are k different colors, and m plates of each color. The goal of the game is to arrange the plates such that each side contains only plates of the same color. The following picture shows a 6-sided puzzle with 6 levels on each side:

You can use the following two actions to solve the puzzle. First, any level can be rotated around the axis of the cylinder in any direction. A single rotation will move each plate on a level to the slot on the next side at the same level. For example, if we take the puzzle from the picture and rotate level 2 (the second from the bottom) in a clockwise direction, the blue plate will move to the green plate's original position, and the yellow plate will take the blue plate's place. Each such rotation takes 1 second. A full turn around the example puzzle would therefore take 6 seconds.

The second allowed action is shifting plates within a single side. If there's an empty slot directly adjacent to a plate on the same side, the plate can be moved into that slot. For example, the bottommost slot on the middle side of the example puzzle (between the red and green plates) is empty, so the blue plate from the second level can be moved to the first level (leaving its original slot on the second level empty). This movement also takes 1 second. Please note that neither the red nor green plate on the bottommost level can be moved to the empty slot because the puzzle is only constructed to allow plates to be shifted within the same side. If we were to rotate the first level counterclockwise, the empty slot would replace the green plate, the red plate would replace the empty slot, etc.

You will be given a String[] puzzle representing the initial state of the puzzle. Each element of puzzle represents one level of the puzzle, with the first k uppercase letters representing the k different colors. The i-th character of each element of puzzle corresponds to the i-th side. You must remove any one plate from the puzzle to create an empty slot and make shifting plates possible. Find the plate which will allow you to solve the puzzle in the minimal time and return this time.

 

Definition

    
Class:PenPuzzle
Method:solve
Parameters:String[]
Returns:int
Method signature:int solve(String[] puzzle)
(be sure your method is public)
    
 

Constraints

-puzzle will contain between 2 and 3 elements, inclusive.
-All elements of puzzle will contain the same number of characters.
-Each element of puzzle will contain between 3 and 4 characters, inclusive.
-Each element of puzzle will contain only the first k uppercase letters, where k is the length of any element of puzzle. All elements of puzzle will contain the same total number of appearances of each of the first k uppercase letters.
 

Examples

0)
    
{"ABC", "ABC"}
Returns: 0
This puzzle is already solved. You can remove any plate and it still will be solved.
1)
    
{"ABC", "BCA"}
Returns: 1
One rotation solves this puzzle.
2)
    
{"ABA", "BCC"}
Returns: 2
The initial state of the puzzle is
ABA
BCC

Remove the second 'A' plate to get to the following configuration ('_' stands for an empty slot):
AB_
BCC

Shift the second 'C' to the upper level:
ABC
BC_

And rotate the upper row to solve the puzzle:
BCA
BC_
3)
    
{"CBBC", "DCAB", "ADAD"}
Returns: 13

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TopologicalEquivalence

Brute Force, Graph Theory



Used in:

TCCC06 Round 3

Used as:

Division I Level Three

Writer:

Yarin

Testers:

PabloGilberto , brett1479 , radeye , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6648

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10111&pm=6648

Problem Statement

    

Consider the figures made up of line segments below. There are 5 connected figures, but only 3 distinct figures if one considers their topological features (the first and second are equivalent, as are the third and fourth). Two figures are considered to be topological equivalent if one of the figures can be deformed by stretching, bending, etc. into the other (but not necessarily in 2D space).

A more formal definition can be expressed in terms of graph theory. A figure can be considered to be an embedding of a multigraph (it may have loops and multiple edges) in the plane, where each vertex has been assigned to a distinct point, and each edge to some polygonal path without self-intersections. We consider two figures to be equivalent if their embeddings could have both originated from the same multigraph. In this problem, we will assume that each edge is disjointly embedded. That is, two embedded edges can only meet at a common endpoint.



Create a class TopologicalEquivalence containing the method countDistinct which takes a set of non-intersecting and non-overlapping line segments and counts the number of distinct connected figures (according to the definition of topological equivalence above). The line segments will be given in a String[] lineSegs, where each element may contain several line segments. A line segment will be given in the form (quotes for clarity) "x1,y1-x2,y2" and within each element they will be single space separated. Two line segments are connected if they share a common endpoint. A figure is a minimal non-empty subset of the line segments such that no line segment in the figure is connected to a line segment not in the figure.

 

Definition

    
Class:TopologicalEquivalence
Method:countDistinct
Parameters:String[]
Returns:int
Method signature:int countDistinct(String[] lineSegs)
(be sure your method is public)
    
 

Constraints

-The line segments making up a figure will have at most 8 distinct end points.
-lineSegs will contain between 1 and 50 elements, inclusive.
-Each element in lineSegs will contain between 7 and 50 characters, inclusive.
-Each element in lineSegs will be a space-separated list of line segments specified in the format above. There will be no leading, trailing, or consecutive spaces.
-The coordinates for each line segment will be integers between 0 and 1000, inclusive, with no extra leading zeros.
-No two line segments will partially overlap or intersect, except at the endpoints.
-All line segments will have a positive length.
 

Examples

0)
    
{"0,7-5,7 5,7-5,2 5,2-0,2 0,2-0,7 5,2-7,0",
 "8,7-15,7 15,7-10,2 10,2-8,7 10,2-10,5 10,5-12,5",
 "16,6-19,2 16,6-22,4 22,4-21,2 21,2-19,4",
 "24,7-24,2",
 "25,5-27,3 27,7-29,5 25,2-27,3 29,2-27,3 25,5-27,7","27,3-29,5"}
Returns: 3
This corresponds to the figures in the pictures. Here, each element correspond to one of the figures (although this is not generally the case, see further examples).
1)
    
{"16,0-17,1 17,1-17,3 17,3-16,4 16,4-14,4 14,4-14,0",
 "9,1-9,3 9,3-10,4 10,4-12,4 12,4-13,3 14,0-16,0",
 "0,4-1,2 1,2-2,0 2,0-3,2 1,2-3,2 3,2-4,4 5,0-7,0",
 "25,0-27,0 24,1-24,3 24,3-25,4 25,4-27,4 27,4-27,2",
 "7,0-8,1 8,1-7,2 7,2-8,3 8,3-7,4 7,4-5,4 5,4-5,2",
 "18,0-20,0 18,0-18,2 18,2-18,3 18,2-18,4 18,4-20,4",
 "21,0-23,0 21,0-21,2 21,2-22,2 21,2-21,4 24,1-25,0",
 "5,2-5,0 5,2-7,2 9,1-10,0 10,0-12,0 12,0-13,1",
 "27,2-25,2 28,0-28,2 28,2-28,4 30,0-30,2 30,2-30,4",
 "28,2-30,2 31,0-31,4"}
Returns: 6
The 9 figures in this input correspond to the letters A, B, C, D, E, F, G, H and I. Topologically, the three letters C, G and I are the same, as well as the two letters E and F. The remaining 4 letters have distinct topological features.
2)
    
{"0,2-2,2 10,2-12,0 2,2-4,0 12,0-14,2",
 "4,0-4,4 14,2-10,2 4,4-2,2 10,2-12,4",
 "4,4-6,2 12,4-14,2 6,2-8,2 12,4-12,6",
 "14,8-12,6 6,2-4,0 12,6-10,8"}

Returns: 2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FastGossip

Dynamic Programming, Graph Theory



Used in:

TCCC06 Semi 2

Used as:

Division I Level Three

Writer:

soul-net

Testers:

PabloGilberto , lbackstrom , brett1479 , Olexiy , Jan_Kuipers

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6624

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10133&pm=6624

Problem Statement

    

There is a group of friends that is not as close as it should be. Not everybody inside the group likes everybody else. One of the friends has some important news that needs to be spread to every member of the group. He has information on who would be willing to call each other and has to develop a strategy to make sure all members of the group receive the news as soon as possible.

Each person can only call one friend each minute, and during that minute, he will transmit the news along with the calling strategy that the receiver should follow. Any person that has already been called is allowed to call other friends, but nobody can be on the phone (passing on or receiving the news) with more than one other person during the same minute.

You will be given a String[] conn, where the jth character of the ith element is 'Y' if the ith friend is willing to call the jth friend, or 'N' otherwise. The 0th person (0-based) is the one that initially learns about the news. Return the least number of minutes needed for the entire group to be aware of the news. If it is impossible for this to happen, return -1.

 

Definition

    
Class:FastGossip
Method:minTime
Parameters:String[]
Returns:int
Method signature:int minTime(String[] conn)
(be sure your method is public)
    
 

Notes

-Note that the fact that one friend is willing to call another does not necessarily imply that the other is willing to call the first. See examples for further clarification.
 

Constraints

-conn will contain between 1 and 14 elements, inclusive.
-Each element of conn will contain exactly N characters, where N is the number of elements in conn.
-Each character of each element of conn will be either 'Y' or 'N'.
-The ith character of the ith element of conn will be 'N'.
 

Examples

0)
    
{"NYNN","NNYN","NNNY","NNNN"}
Returns: 3
Individual 0 must call individual 1. Individual 1 must call individual 2. Individual 2 must call individual 3. Since all these actions must happen sequentially, the total time to reach the last individual is 3 minutes.
1)
    
{"NYYY",
 "YNYY",
 "YYNY",
 "YYYN"}
Returns: 2
Everybody is a close friend. Individual 0 can call any one of the other individuals in the first minute, and during the second minute, both of them can call one of the remaining two.
2)
    
{"NN","YN"}
Returns: -1
Individual 0 can't call anybody, and therefore, it is impossible to spread the news to individual 1.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RoboRace

Dynamic Programming, Graph Theory, Search



Used in:

SRM 316

Used as:

Division I Level Three

Writer:

_efer_

Testers:

PabloGilberto , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6621

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9996&pm=6621

Problem Statement

    

You are playing a game with a friend involving two robots on a rectangular board. Each cell of the board is either empty, an obstacle, a starting point for a robot, or the destination. You win the game only if your robot is the first to reach the destination cell. Note that if both robots reach the destination cell at the same time or if neither reaches the destination at all, you lose.

Both robots listen to the following movement commands:

- 'S' -- move south (the current row increases by one)

- 'N' -- move north (the current row decreases by one)

- 'E' -- move east (the current column increases by one)

- 'W' -- move west (the current column decreases by one)

During one time unit, the same movement command is given to both robots. A robot may choose to follow the command given or ignore it. Note that if the command makes the robot leave the board, or enter a cell occupied by an obstacle, it is automatically ignored and that both robots can be in the same cell at the same time. The robots will always make an optimal decision so that they reach the destination cell as soon as possible.

You will be given a String[] board. Each character in board will represent a single cell on the game board and will be either '.' denoting an empty space, '#' denoting an obstacle, 'Y' denoting the starting point for your robot, 'F' denoting the starting point for your friend's robot, or 'X' denoting the destination cell. You will also be given a String[] commands. You should concatenate all elements of commands and make a long String of commands. The ith character of this string will represent the command given during the ith time unit. Starting the game at time 0 (in other words, from the first character of the string of commands) may not guarantee that your robot wins the race. Return the earliest starting time that will guarantee your robot will win. Starting the race at time T means that only the commands starting at index T in the input string are given, the ones with lower indexes will be ignored by both robots. If there is no starting time that can make your robot win, return -1.

 

Definition

    
Class:RoboRace
Method:startTime
Parameters:String[], String[]
Returns:int
Method signature:int startTime(String[] board, String[] commands)
(be sure your method is public)
    
 

Constraints

-board will contain between 1 and 50 elements, inclusive.
-Each element of board will contain between 1 and 50 characters, inclusive.
-All elements of board will contain the same number of characters.
-Each character of each element of board will be either '.', '#', 'Y', 'F' or 'X'.
-The characters 'Y', 'F' and 'X' will each appear exactly once in board.
-commands will contain between 1 and 50 elements, inclusive.
-Each element of commands will contain between 1 and 50 characters, inclusive.
-Each character of each element of commands will be either 'S', 'N', 'E' or 'W'.
 

Examples

0)
    
{"#F",
 "YX"}
{"NES"}
Returns: 0
Your robot needs to move east to reach the destination, while your friend's robot needs to move south. You have three options: start the race at times 0, 1, or 2. If you start the race at time 2, your friend will win. If the race starts at time 0, both robots will have no choice but to ignore the first command, and your robot will win by following the second command. From the two options that guarantee your robot wins, choose the first one, at time 0.
1)
    
{"########",
 "#......#",
 "#.Y....#",
 "#.F.#..#",
 "#...X..#",
 "#...#..#",
 "#......#",
 "########"}
{"SSEEESSW"}
Returns: 2
Start the race at time 2 and your robot will follow the last 6 commands and reach the destination. Your friend's robot needs one of the first two 'S' commands, so you can not start the race sooner than time 2.
2)
    
{"########",
 "#......#",
 "#.Y....#",
 "#.F.#..#",
 "#...X..#",
 "#...#..#",
 "#......#",
 "########"}
{"ESSEESSW"}
Returns: -1
The only way for your robot to reach the destination is to start the race at time 0. However, the other robot will reach the destination sooner in this case.
3)
    
{"##.#.#.",
 "..##...",
 "..#...X",
 "Y...##.",
 "#...#.#",
 "..#..F."}
{"SSSNWSSSEWNSENENENNNNENWNEWESE"}
Returns: 5
If the race starts at time 5, the destination is reached at time 26. The commands followed by your robot are EEENEEE (the others are ignored). Note that starting the race at time 4 would result in both robots reaching the destination cell at the same time.
4)
    
{"#..#.........#...X##....",
 "#........#..........##.#",
 ".#.#........#.....#.#...",
 "..###...#..##.##...#....",
 "..#.#.....#....#.#.####.",
 "#...##.##.##..#.....##..",
 ".##...#.#....#.......#.#",
 "....##.#..#....#....#...",
 "....###.##.....###...#..",
 "#.#.......#.#......#..#.",
 ".##....##.#.##.......#.#",
 "......###...####......#.",
 "..#.##.#..#.#...#...#...",
 ".....#.#..........#...#.",
 "##.#....##F#.....#.##.#.",
 ".##....#.......##.##.##.",
 "..#...#..##....#..#...Y.",
 "#...........#...###..###",
 ".....#...#..#.........#.",
 ".#...##..#.#...#..#.##..",
 "#..#...######....###.#..",
 "#.#.....#.......#.##....",
 "#..#....###....#.#..#...",
 "..#...#.##.##.#.##.##..#",
 "#....##.##..........#..#"}
{"NWWSEWSSNWESSWES",
 "ESEEENSNWNNWSNSNWWNWWNNNWE",
 "NSNENENNSEENWWNSNNNNWWSSN",
 "EENEWNWESESEEESNNNSEENNEWNNESNEESSEESEEENENNNWSSW",
 "NWNNWSNWSWSSSSEEWSSWSESWWNNWWENSNNWWSSWWNNE",
 "NWEWNEWSNEN",
 "NNNEWNSWSNWESWNNNSWWNNNWWWNNEWNEEWSSWNSSWWNNWESEWS",
 "WSSSEESSEEEEENNSWEWWWENSENWNSEENES",
 "NNSNESESWNESNENSEESESWSENNESESNESNESEEW",
 "ESNENEENWSNS"}
Returns: 18

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MarriageProblemRevised

Graph Theory, Math



Used in:

SRM 356

Used as:

Division I Level Two

Writer:

Pawa

Testers:

PabloGilberto , brett1479 , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6608

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10765&pm=6608

Problem Statement

    There are several unmarried men and women living in a society where marriage is defined as either one husband with one or more wives, or one wife with one or more husbands. You are given a String[] preferences. The j-th character of the i-th element of preferences is '1' (one) if the i-th man and the j-th woman are willing to be part of the same marriage, and '0' (zero) otherwise.

Your task is to group these people into the minimum possible number of marriages. Each person must be a member of exactly one marriage, and each marriage must contain only willing members. Return the number of marriages, or -1 if this is not possible.
 

Definition

    
Class:MarriageProblemRevised
Method:neededMarriages
Parameters:String[]
Returns:int
Method signature:int neededMarriages(String[] preferences)
(be sure your method is public)
    
 

Constraints

-preferences will contain between 1 and 12 elements, inclusive.
-The length of each element of preferences will be betwen 1 and 12, inclusive.
-All elements of preferences will be of the same length.
-Each element of preferences will contain only '0' (zeroes) and '1' (ones).
 

Examples

0)
    
{"111"}
Returns: 1
Here, we have one man and three women, and everybody is willing to be in the same marriage. Therefore, we only need one marriage.
1)
    
{"100", "010", "001"}
Returns: 3
2)
    
{"00", "00"}
Returns: -1
Nobody is willing to be in the same marriage as anybody else, so there cannot be any marriages in this case.
3)
    
{"0001", "0001", "0001", "1111"}
Returns: 2
4)
    
{"11101011","00011110","11100100","01010000","01000010","10100011","01110110","10111111"}
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

UnrepeatableWords

Brute Force, Search



Used in:

SRM 323

Used as:

Division II Level Three

Writer:

Pawa

Testers:

PabloGilberto , brett1479 , Olexiy , lovro

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6603

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10003&pm=6603

Problem Statement

    For a given integer k, we call a string S k-unrepeatable if there is no substring that appears k consecutive times in S.

For example, the string CCABAABAABAC is 4-unrepeatable. But it's not 3-unrepeatable, because the string ABA appears in it 3 times in a row. CCABAABACABA and ABABAABA are examples of 3-unrepeatable strings.

You are given three integers, k, n and allowed. Return the lexicographically smallest k-unrepeatable word of length n that uses only the first allowed uppercase characters of the English alphabet. If no such word exists, return the empty string.
 

Definition

    
Class:UnrepeatableWords
Method:getWord
Parameters:int, int, int
Returns:String
Method signature:String getWord(int k, int n, int allowed)
(be sure your method is public)
    
 

Constraints

-k will be between 2 and 10, inclusive.
-n will be between 1 and 50, inclusive.
-allowed will be between 1 and 26, inclusive.
 

Examples

0)
    
3
5
2
Returns: "AABAA"
All lexicographically smaller strings of length 5 contain three consecutive occurrences of the letter A, so they aren't 3-unrepeatable.
1)
    
3
5
1
Returns: ""
The only possible string is AAAAA, which is not 3-unrepeatable.
2)
    
3
10
2
Returns: "AABAABABAA"
3)
    
3
50
2
Returns: "AABAABABAABAABBAABAABABAABAABBAABAABABAABABBAABAAB"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SetOfBoxes

Geometry, Graph Theory, String Parsing



Used in:

TCHS SRM 15

Used as:

Division I Level Three

Writer:

Vedensky

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6596

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10067&pm=6596

Problem Statement

    You have a large square box and some smaller triangular boxes (all two-dimensional). The triangular boxes all lie inside the square box. Triangular boxes may lie inside other triangular boxes, but they must not overlap. You randomly throw an object (represented as a point) into the square box, and you want to know if it lands inside exactly inBox triangular boxes.



You are given a String[] boxes, each element of which is formatted as "X1.Y1 X2.Y2 X3.Y3" (quotes for clarity only), representing the three corners of a triangular box. The large square box has sides parallel to the axes, and has corners at (0, 0) and (100, 100). Return the probability (between 0 and 1) that a random point within the square is contained in exactly inBox triangular boxes.
 

Definition

    
Class:SetOfBoxes
Method:countThrow
Parameters:String[], int
Returns:double
Method signature:double countThrow(String[] boxes, int inBox)
(be sure your method is public)
    
 

Notes

-Your return value must have an absolute or relative error less than 1e-9.
 

Constraints

-boxes will contain between 0 and 50 elements, inclusive.
-Each element of boxes will be formatted as "X1.Y1 X2.Y2 X3.Y3" (quotes for clarity only).
-X1, Y1, X2, Y2, X3, Y3 will be integers with no leading zeros, each between 0 and 100, inclusive.
-Triangles represented by different elements of boxes will have no common points.
-inBox will be between 0 and 50, inclusive.
 

Examples

0)
    
{"0.0 1.0 0.1"}
1
Returns: 5.0E-5
1)
    
{"0.0 20.0 0.10", "1.1 6.1 1.5"}
1
Returns: 0.0090
Here it is the area of the first triangle minus the area of the second one.
2)
    
{"0.0 10.0 0.20", "0.100 0.90 20.100", "50.50 60.60 50.70", "51.55 55.60 51.65"}
1
Returns: 0.028
3)
    
{"0.0 10.0 0.20", "0.100 0.90 20.100", "50.50 60.60 50.70", "51.55 55.60 51.65"}
0
Returns: 0.97

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TextEditorNavigation

Graph Theory, Simulation



Used in:

TCHS SRM 5

Used as:

Division I Level Three

Writer:

Uranium-235

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6571

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10057&pm=6571

Problem Statement

    When programming, I don't like to take my fingers off the keyboard, and hence, I don't use the mouse. So, when navigating my source, I like to do so in such a way as to minimize keystrokes. My text editor supports the following keystrokes: left, right, up, down, home, end, top, bottom, word left and word right. The word left and word right keystrokes position the cursor at a word beginning; a word beginning is the first letter of the word. None of the keystrokes cause the cursor to wrap. When moving the cursor vertically, my text editor does not change the cursor's horizontal position. So, if the cursor is at column 50 and the up arrow is pressed, moving the cursor to a row with only 10 characters, only the row changes. My text editor does not allow the cursor to be positioned left of the first column, above the first row or below the last row.



The keys left, right, up, down, home, end, top, bottom, word left and word right behave as described below:



1. left, right, up and down - move the cursor one position in the indicated direction (see notes).

2. home - causes the cursor to move to column 0 of the current row.

3. end - causes the cursor to move to the last character of source in the current row.

4. top - causes the cursor to move to the top row (row 0) retaining its column position.

5. bottom - causes the cursor to move to the bottom row retaining its column position.

6. word left - causes the cursor to jump to the first word beginning that is strictly left of the cursor position, if one exists. Otherwise does nothing.

7. word right - causes the cursor to jump to the first word beginning that is strictly right of the cursor position, if one exists. Otherwise does nothing.



You will be given a String[] source representing the source code, a int[] start representing the starting position of the cursor and a int[] finish representing the ending position of the cursor. The first int in both start and finish specifies the 0-indexed row and the second int specifies the 0-indexed column. You are to calculate and return the minimum number of keystrokes required to get from start to finish.
 

Definition

    
Class:TextEditorNavigation
Method:keystrokes
Parameters:String[], int[], int[]
Returns:int
Method signature:int keystrokes(String[] source, int[] start, int[] finish)
(be sure your method is public)
    
 

Notes

-For the purposes of this problem, we use the convention that the cursor covers each character. Some editors (normally in "insert mode") have the cursor preceding each character.
-A keypress may not have any effect. For example, pressing up in the top row does nothing, pressing left in the first column does nothing and pressing down in the bottom row does nothing. Pressing right always has an effect.
 

Constraints

-source will contain between 1 and 50 elements, inclusive.
-Each element of source will contain between 1 and 50 characters, inclusive.
-Each character must be a letter ('a'-'z', 'A'-'Z') or ' '.
-start and finish will each contain exactly 2 elements.
-start and finish will each represent character positions that exist in source.
 

Examples

0)
    
{"AAAAA AAA AAAAAAAAAAAAA  AAAA",
 "AA   AAAAAAAAA AAAA     AAAA",
 "BBBBBBBBBBBBBBBBBBBBBBBBBBB",
 "BBBBBBB BBBBBBBBBB BBBBBBB",
 "CCC CCCC CCCCCC      CCCC",
 "DDDDDDDDDDDDDDDDDDD"}
{5, 7}
{2, 2}
Returns: 6
This can be achieved by the following keystrokes in the given order: home, top, down, down, right, right.
1)
    
{"A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "BB BB BB BB BB BB BB BB BB BB BB BB BB BB BB BB BB",
 "CCC CCC CCC CCC CCC CCC CCC CCC CCC CCC CCC CCC CC",
 "DDDD DDDD DDDD DDDD DDDD DDDD DDDD DDDD DDDD DDDD ",
 "EEEEE EEEEE EEEEE EEEEE EEEEE EEEEE EEEEE EEEEE EE",
 "FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF ",
 "GGG GGG GGG GGG GGG GGG GGG GGG GGG GGG GGG GGG GG",
 "HHHHHHHHHHH HHHHHHHHHH HHHHHHHHHH HHHHHHHHHH HHHHH",
 "IIIIIIIIIIIIIII IIIIIIIIIIIIIII IIIIIIIIIIIIIII   ",
 "JJJJJJJJ JJJJJJJJ JJJJJJJJ JJJJJJJJ JJJJJJJJ JJJJJ",
 "KKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKK",
 "LLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL",
 "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM",
 "N N N N N N N N N N N N N N N N N N N N N N N N N ",
 "OOOOO OOOO OOO OO O O OO OOO OOOO OOOOO OOOOOO OOO",
 "PPPPPPP PPPPPP PPPPP PPPP PPP PP P P PP PPP PPPP P",
 "QQQQQQ QQQQQ QQQQ QQQ QQ Q Q QQ QQQ QQQQ QQQQQ QQQ",
 "ZZZZ ZZ ZZZ ZZ ZZZZ ZZ ZZZ ZZ ZZZZ ZZ ZZZ ZZ ZZZZ ",
 "SSS S SSS S SSS S SSS S SSS S SSS S SSS S SSS S SS",
 "TT TT TT TT TT TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT"}
{12, 20}
{4, 36}
Returns: 8
2)
    
{"A A A A AAAAAAA A A A A A A A A A A",
 "B BBBBB B B B B BBBBB B B B B B B B B"}
{1, 0}
{1, 22}
Returns: 6
3)
    
{"AAAAAAAAAAAAAA A A A A A A A A A A"}
{0, 2}
{0, 15}
Returns: 1
4)
    
{"A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "N N N N N N N N N N N N N N N N N N N N N N N N N ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 "A A A A A A A A A A A A A A A A A A A A A A A A A ",
 " O O O O O O O O O O O O OO O O O O O O O O O O O ",
 " P P P P P P P P P P P P P PP P P P P P P P P P P ",
 " Q Q Q Q Q Q Q Q Q Q Q Q Q Q QQ Q Q Q Q Q Q Q Q Q ",
 " R R R R R R R R R R R R R R R RR R R R R R R R R ",
 " S S S S S S S S S S S S S S S S SS S S S S S S S ",
 " T T T T T T T T T T T T T T T T T TT T T T T T T ",
 " U U U U U U U U U U U U U U U U U U UU U U U U U ",
 " V V V V V V V V V V V V V V V V V V V VV V V V V ",
 " W W W W W W W W W W W W W W W W W W W W WW W W W ",
 " X X X X X X X X X X X X X X X X X X X X X XX X X ",
 " Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y YY Y ",
 " Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z ZZZ"}
{49, 49}
{38, 26}
Returns: 23
5)
    
{"AAA", "BB", "CCC"}
{1, 1}
{1, 1}
Returns: 0
6)
    
{"AAAAA AAA AAAAAAAAAAAAA  AAAA",
 "AA   AAAAAAAAA AAAA     AAAA",
 "BBBBBBBBBBBBBBBBBBBBBBBBBBB",
 "BBBBBBB BBBBBBBBBB BBBBBBB",
 "CCC CCCC CCCCCC      CCCC",
 "DDDDDDDDDDDDDDDDDDD"}
{2, 17}
{1, 2}
Returns: 4
7)
    
{"A PC to do CAD huh  Sounds reasonable",
 "Aurthor go out and buy us five new PCs",
 "Dont you want to think about this for a minute",
 "No every second counts and we want to be ahead of",
 "the competition",
 "       OK Greate idea Please place lOOk worth of",
 "unmarked bills in my suitcase and Ill be on my way"}
{0, 11}
{1, 15}
Returns: 2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SuperSort

Sorting, String Manipulation, String Parsing



Used in:

TCHS SRM 5

Used as:

Division I Level Two

Writer:

Uranium-235

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6568

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10057&pm=6568

Problem Statement

    A sentence is composed of words, spaces and punctuation. For this problem, words are maximal contiguous strings of letters. Given a sentence, sort the words in the sentence while preserving the spaces and punctuation. Sorting is case sensitive, so uppercase letters precede lowercase letters. Return the newly constructed sentence.



Example:
	"The big,  brown   dog    ran   down  the street!"
Returns:
	"The big,  brown   dog    down   ran  street the!"
Observe the space and punctuation preservation between the original sentence and the resulting sentence.
 

Definition

    
Class:SuperSort
Method:wordSort
Parameters:String
Returns:String
Method signature:String wordSort(String sentence)
(be sure your method is public)
    
 

Notes

-Watch out for multiple consecutive spaces (they should be preserved).
 

Constraints

-sentence will contain between 1 and 50 characters, inclusive.
-Each character in sentence will be either a letter ('a'-'z', 'A'-'Z'), ' ', '.', ',', '!' or '?'.
 

Examples

0)
    
"The big,  brown   dog    ran   down  the street!"
Returns: "The big,  brown   dog    down   ran  street the!"
1)
    
"This is the first sentence of the paragraph."
Returns: "This first is of paragraph sentence the the."
2)
    
"t.d,a!f?g.b,q!i?p.h,s!u?m.l,e!v?y.c,j!w?k.n,x!o?r."
Returns: "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."
3)
    
"What is this?"
Returns: "What is this?"
4)
    
"?   .   ,   !   "
Returns: "?   .   ,   !   "
5)
    
"                    "
Returns: "                    "
6)
    
"faecdb"
Returns: "faecdb"
7)
    
"a A b B c C d D e E"
Returns: "A B C D E a b c d e"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BasketballStrategy

Geometry, Graph Theory, Math



Used in:

SRM 313

Used as:

Division I Level Three

Writer:

soul-net

Testers:

PabloGilberto , brett1479 , legakis , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6546

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9993&pm=6546

Problem Statement

    

This problem statement contains images, subscripts and superscripts that may appear incorrectly or not appear at all in some plugins. In that case, use the standard view in the arena to see it correctly.

In a simplified version of basketball the goal is to score by getting the ball in a special scoring place. There are two teams, and each team contains the same number of players. When a player has possession of the ball, he has two choices: take a shot, or pass the ball to a teammate. When taking a shot, the player throws the ball in a straight line to the scoring place. When passing the ball, he throws the ball in a straight line to the target teammate. In both cases, at most one of the rival players will try to intercept the shot or pass.

The probability of a pass being successful is:

Cp * (1 - (ls / 150)2) * dr / (dr + 1)

And the probability of a shot being successful (score) is:

(Cs * dr / (dr + 1))ln(ls)

Where Cp and Cs are constants defined for the problem instance, ls is the length of the shot or pass, dr is the distance between the intercepting rival and the ball trajectory and ln is the natural logarithm (logarithm in base e).

When trying to intercept a shot or a pass, only the best suitable player of the other team to do so (i.e., the one that produces the lowest dr) will try. If no player on the other team can do it, the factor dr/(dr+1) in the formula is considered to have a value of 1 (i.e., it is ignored). A player of the rival team is only allowed to try to intercept the ball if the line that passes through him and is perpendicular to the ball trajectory intersects the trajectory at some point between the two endpoints of the trajectory, inclusive.

For example, in this picture:



There are 3 players in each team, green players are your team and red players are rivals. Player 0 has the ball and has 3 options marked as blue lines, 2 passes and taking a shot. The shot, if taken, can be intercepted by any of the rivals, but only number 2 will try because he is clearly the nearest. The pass to player 1 is impossible to intercept for the rivals, because any player that can intercept that pass should be inside the gray area. The pass to player 2 can be intercepted by rivals 1 or 2. Rival player 0 is not on an intersecting perpendicular line, so he cannot try to intercept it. In this last case, rival 1 will try to intercept because he is nearer than rival 2.

You will be given two String[]s team and rivals with the same number of elements representing the members of each team. Each element of team and rivals will be in the format "X Y" where X and Y will be positive integers with no leading zeroes representing the x and y coordinates of that player in the field. You will also be given Cp and Cs, the constants for the probability calculations of each type of movement. When the game starts, the ball is in possession of the player on your team with index 0. The scoring place is at X=50, Y=0. Your team is only allowed to take one shot, and you are to determine and return the probability that your team will score if it follows the best strategy. A strategy consists of zero or more passes followed by a shot. If your team loses the ball at any point during the strategy, you will not score. See examples for further clarification.

 

Definition

    
Class:BasketballStrategy
Method:scoreProbability
Parameters:String[], String[], double, double
Returns:double
Method signature:double scoreProbability(String[] team, String[] rivals, double Cp, double Cs)
(be sure your method is public)
    
 

Notes

-The returned value must be accurate to within a relative or absolute value of 1E-9.
-Pictures are just approximations. The players are considered to be perfect points with 0 surface and 0 length and trajectories and other lines are perfect lines with 0 surface.
-The same rival may try to intercept many passes along the game (see example 3 for further clarification).
 

Constraints

-team and rivals will each contain exactly N elements, where N is between 1 and 50, inclusive.
-Each element of team and rivals will be two integers between 1 and 99, inclusive, with no leading zeroes, separated with exactly one space character, with no leading or trailing spaces.
-All elements of team and rivals together will be distinct.
-Cp and Cs will each be greater than 0 and less than or equal to 1.
 

Examples

0)
    
{"50 50","35 60","70 15"}
{"75 5","72 25","45 17"}
1
1
Returns: 0.6100612919616956
This is the example from the problem statement. The best strategy is to pass the ball to player 2 and make him shoot.
1)
    
{"50 4"}
{"50 5"}
0.99
0.5
Returns: 0.3825461314703953
There's no teammate to pass the ball to, so you must take the shot directly. Since the only rival player is not in a position to intercept, the probability of making the shot is 0.5ln(4).
2)
    
{"50 4"}
{"50 3"}
0.5
0.5
Returns: 0.0
You can't pass the ball and your rival can perfectly block you; therefore it's impossible to score.
3)
    
{"50 50","40 50","40 40","40 30","50 20"}
{"50 41","44 29","48 27","45 41","48 64"}
0.999999
0.8
Returns: 0.25546407305110735
This picture illustrates the locations. The best strategy is marked in blue and the pink lines show possible interception lines from a nearest rival. Note that passes 2-3 and the shot taken by player 4 cannot be intercepted.



Here player 0 cannot take a shot because he will always be blocked. You should try to get the ball to player 4 so he can take the shot instead. Note that in this case it is better to make more passes and get to player 4 for the shot because the difficulty of longer passes and shots makes other strategies less likely to succeed.
4)
    
{"50 50","50 25"}
{"40 40","60 20"}
1
0.7
Returns: 0.20631213370921644
Note that getting closer can be better even if you are good at taking shots.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RPSTournament

Graph Theory, Greedy, Search



Used in:

SRM 339

Used as:

Division I Level Three

Writer:

_efer_

Testers:

PabloGilberto , brett1479 , radeye , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6539

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10663&pm=6539

Problem Statement

    

You are organizing a local Rock-Paper-Scissors Tournament, where the best N players in your town will compete for fame and prizes. You have already ranked the participants according to their performance in the qualifying round, so each one of them will have a seed for winning the tournament in the range from 1 to N.

The tournament will be in a knockout format and will consist of multiple rounds. During each round the competitors still left in the competition are randomly paired up with each other. The winners from each game advance to the next round. The great champion is the winner of the final game between the last two remaining players.

The tournament starts soon, and you are preoccupied with some pre-statistics. You estimate that a player with any seed S can win against players with greater seeds, and against ones with lower seeds, if the difference between their seeds is not greater than sqrt(C * S), where C is a constant. Assuming that the outcome of all the played games during the tournament agrees with your estimation, a player can win the tournament if there exists an assignment of games in each of the rounds such that the player can win each round.

You will be given two ints, rounds, denoting the number of rounds, and the constant C. Return the greatest seed of a player that could win the tournament. Note that N, the number of competitors will be N = 2rounds.

 

Definition

    
Class:RPSTournament
Method:greatestSeed
Parameters:int, int
Returns:int
Method signature:int greatestSeed(int rounds, int C)
(be sure your method is public)
    
 

Constraints

-rounds will be between 1 and 16, inclusive.
-C will be between 0 and 1500, inclusive.
 

Examples

0)
    
2
0
Returns: 1
There is no room for surprises here. Since nobody can win against a higher-rated opponent, the lowest seed will win the tournament.
1)
    
3
1
Returns: 6
Player 2 can win against player 1, so both of them can win the final if they are to meet in that phase of the competition. Since players 3 and 4 can beat player 2, they can win the tournament as long as player 2 wins against player 1 somewhere before the final. Finally, players 5 and 6 can beat player 4 in the final, as long as player 4 wins against player 2 in the semifinals and player 2 eliminates player 1 in the first round. It is impossible for players 7 and 8 to win the tournament. We return the greatest seed of those who can win, namely 6.
2)
    
4
1
Returns: 9
3)
    
7
3
Returns: 50
4)
    
15
180
Returns: 9755
Watch out for timeout!

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SpreadingNews

Graph Theory, Greedy, Recursion



Used in:

SRM 316

Used as:

Division II Level Three

Writer:

_efer_

Testers:

PabloGilberto , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6538

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9996&pm=6538

Problem Statement

    

You are the manager of a company, and you want all of your employees to be notified of an important news item as quickly as possible. Your company is organized in a tree-like structure: each employee has exactly one direct supervisor, no employee is his own direct or indirect supervisor, and every employee is your direct or indirect subordinate. You will make a phone call to each of your direct subordinates, one at a time. After hearing the news, each subordinate must notify each of his direct subordinates, one at a time. The process continues this way until everyone has heard the news. Each person may only call direct subordinates, and each phone call takes exactly one minute. Note that there may be multiple phone calls taking place simultaneously. Return the minimum amount of time, in minutes, required for this process to be completed.

Employees will be numbered starting from 1, while you will be numbered 0. Furthermore, every supervisor is numbered lower than his or her direct subordinates. You are given a int[] supervisors, the ith element of which is the direct supervisor of employee i. The first element of supervisors will be -1, since the manager has no supervisors.

 

Definition

    
Class:SpreadingNews
Method:minTime
Parameters:int[]
Returns:int
Method signature:int minTime(int[] supervisors)
(be sure your method is public)
    
 

Constraints

-supervisors will contain between 1 and 50 elements, inclusive.
-Element i of supervisors will be between 0 and i-1, inclusive, except for the first element which will be -1.
 

Examples

0)
    
{-1, 0, 0}
Returns: 2
Call subordinate 1 at time 0 and then subordinate 2 at time 1. By time 2, both subordinates will have heard the news.
1)
    
{-1, 0, 0, 2, 2}
Returns: 3
This time call employee 2 first, and then employee 1 at time 1. After hearing the news, employee 2 will call employee 3 at time 1 and employee 4 at time 2. It takes 3 minutes for everybody to hear the news.
2)
    
{-1, 0, 1, 2, 3}
Returns: 4
Everyone in the company has only one subordinate, resulting in a chain of phone calls.
3)
    
{-1, 0, 0, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 7, 8, 12, 13, 14, 16, 16, 16}
Returns: 7

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ParallelProgramming

Dynamic Programming, Graph Theory



Used in:

SRM 313

Used as:

Division II Level Three

Writer:

soul-net

Testers:

PabloGilberto , brett1479 , legakis , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6517

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9993&pm=6517

Problem Statement

    

You are programming the process scheduler for an operating system that controls many processors. The parallelism achieved by this new system is total, meaning that any number of processes can run at the same time without disturbing each other. Of course, certain processes may need some other processes to end before they start.

You will be given the execution time of each process as a int[], where the ith element is the number of milliseconds the ith process takes to complete execution. The information about precedences will be given as a String[] prec, where the jth character of the ith element is 'Y' if process j needs process i to be finished before executing itself and 'N' otherwise. Return the minimum number of milliseconds needed for all processes to be finished. If it's impossible for all the processes to finish, return -1.

 

Definition

    
Class:ParallelProgramming
Method:minTime
Parameters:int[], String[]
Returns:int
Method signature:int minTime(int[] time, String[] prec)
(be sure your method is public)
    
 

Constraints

-time will contain between 1 and 50 elements, inclusive.
-time and prec will contain the same number of elements.
-Each element of time will be between 1 and 1000, inclusive.
-Each element of prec will contain exactly N characters, where N is the number of elements in prec.
-Each element of prec will contain only 'N' and 'Y'.
-The ith character of the ith element of prec will be 'N'.
 

Examples

0)
    
{150,200,250}
{"NNN",
 "NNN",
 "NNN"}
Returns: 250
In this case, all processes can run in parallel, so after 250 milliseconds, they will all finish.
1)
    
{150,200,250}
{"NNN",
 "YNN",
 "NNN"}
Returns: 350
In this case, process 0 has to wait for process 1 to end, so the finishing time of process 0 cannot be sooner than 350. Process 2 can execute at any time during those 350 milliseconds because it has no precedence relationships.
2)
    
{150,200,250}
{"NYN",
 "NNY",
 "NNN"}
Returns: 600
In this case there is no parallelism, so the three processes need to be executed in the sequence 0-1-2.
3)
    
{150,200,250}
{"NYN",
 "NNY",
 "YNN"}
Returns: -1
No process can begin execution here because all of them are waiting for another process to finish. Therefore, it is impossible for all of the processes to finish.
4)
    
{345,335,325,350,321,620}
{"NNNNNN",
 "NNYYYY",
 "YNNNNN",
 "NNYNYN",
 "NNNNNN",
 "NNNNNN"}
Returns: 1355

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

StudentsOrdering

Sorting, String Manipulation



Used in:

TCCC06 Qual 1

Used as:

Division I Level Two

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6505

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10093&pm=6505

Problem Statement

    

You want to arrange a group of students so that their heights are in non-descending order, and boys and girls alternate with each other.

You will be given a String[] students. Each element of students will be in the format "name height sex" (quotes for clarity only), where height is an integer in centimeters and sex is either "boy" or "girl" (quotes for clarity only). Return a String containing a dash-separated list of the students' names in the desired order. If multiple return values are possible, return the one that comes first lexicographically. If there is no possible ordering, return "" (empty String). Note that dashes ('-') come earlier lexicographically than letters.

 

Definition

    
Class:StudentsOrdering
Method:findOrder
Parameters:String[]
Returns:String
Method signature:String findOrder(String[] students)
(be sure your method is public)
    
 

Constraints

-students will contain between 1 and 50 elements, inclusive.
-Each element of students will be contain between 1 and 50 characters, inclusive.
-Each element of students will be formatted as described in the problem statement.
-The name of each student will consist of letters ('A'-'Z', 'a'-'z') only.
-The height of each student will be between 100 and 250, inclusive.
-The height of each student will contain no leading zeroes.
 

Examples

0)
    
{"Alex 180 boy", 
 "Josh 181 boy", 
 "Mary 158 girl", 
 "An 158 girl", 
 "Tanya 180 girl", 
 "Ted 158 boy"}
Returns: "An-Ted-Mary-Alex-Tanya-Josh"
1)
    
{"Alex 180 boy", 
 "Josh 158 boy", 
 "Mary 180 girl", 
 "An 158 girl", 
 "Mary 180 girl", 
 "Ted 158 boy"}
Returns: "Josh-An-Ted-Mary-Alex-Mary"
Student names can repeat.
2)
    
{"Alex 180 boy", 
 "Josh 170 boy", 
 "An 158 girl", 
 "Mary 180 girl", 
 "Ted 175 boy"}
Returns: ""
There is no girl to place between Josh and Ted.
3)
    
{"Mary 175 girl"}
Returns: "Mary"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AntarcticaPolice

Graph Theory, Simple Math



Used in:

SRM 312

Used as:

Division I Level Two

Writer:

Petr

Testers:

PabloGilberto , brett1479 , Yarin , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6501

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9992&pm=6501

Problem Statement

    

Year 2100. Humanity is starting to inhabit Antarctica. So far there are N towns, some of them connected with narrow one-way roads.

The president of Antarctica has decided to establish police in his country. The cost of building a police station in each town is given. However, there may not be a need to build a police station in every town. The only requirement is that every town must be reachable from some police station using roads.

As the next elections are approaching, the president doesn't want to expose large police expenses. Thus he wants the average cost of a built station to be as low as possible.

You are given a int[] costs, the i-th element of which represents the cost of building a police station in town i, and a String[] roads representing the layout of the one-way roads. The j-th character of the i-th element of roads is 'Y' if there is a road from town i to town j, or 'N' if there is not. Make the average cost of a built station to be as low as possible and return this cost.

 

Definition

    
Class:AntarcticaPolice
Method:minAverageCost
Parameters:int[], String[]
Returns:double
Method signature:double minAverageCost(int[] costs, String[] roads)
(be sure your method is public)
    
 

Notes

-The returned value must be accurate to within a relative or absolute error of 1E-9.
 

Constraints

-costs will contain between 1 and 50 elements, inclusive.
-Each element of costs will be between 1 and 1000, inclusive.
-roads will contain exactly N elements, where N is the number of elements in costs.
-Each element of roads will contain exactly N characters.
-Each character of each element of roads will be 'Y' or 'N'.
-The ith character of the ith element of roads will be 'N'.
 

Examples

0)
    
{1,2,3,4}
{"NYNN","NNYN","NNNY","YNNN"}
Returns: 1.0
It is possible to get everywhere from anywhere (the towns form a big circle), so we need only the cheapest station.
1)
    
{1,2,3,4}
{"NYNN","NNYN","NNNY","NYNN"}
Returns: 1.0
Once again, the cheapest station is enough.
2)
    
{5,6,7,8}
{"NYNN","YNNN","NNNY", "NNYN"}
Returns: 6.0
We have two separate parts, so we build one cheapest station in each part : (5+7)/2=6.
3)
    
{10,5}
{"NY","NN"}
Returns: 7.5
We have three choices here: build a police station in town 0, in town 1, or in both towns. The second choice doesn't satisfy the requirements since it's impossible to get from town 1 to town 0. Of the two remaining choices, building both is better because it minimizes the average cost.
4)
    
{34,22,25,43,12}
{"NYNNY","YNNYN","NNNYY","NNNNN","NNNNN"}
Returns: 19.666666666666668

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CornersGame

Graph Theory



Used in:

SRM 308

Used as:

Division I Level Two

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6475

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9988&pm=6475

Problem Statement

    

This problem contains an image that can be viewed in the applet.

A player has four draughts which are placed in the bottom right corner of a 6 x 6 chessboard. The draughts are arranged in a square with 2 rows and 2 columns (see picture below). Some cells on the board may contain red flags, and some may contain stones.

The player's goal is to move all the draughts to the top left corner and arrange them in a square using a minimal number of moves. The draughts are indistinguishable, so their order in the final position doesn't matter. The target cells are guaranteed to be free. There are two kinds of moves that can be made by a draught. The first is to move to any vertically or horizontally adjacent free cell. The second is to jump over a single vertically or horizontally adjacent draught or stone into a free cell. The player can never move a draught into a cell that contains a flag, stone or other draught and he can never jump over a flag or an empty space.

You will be given a String[] board where each element represents a single row of the chessboard. The rows are given from top to bottom, and each row is given from left to right. '.' represents a free cell, 'r' represents a cell with a red flag, and 's' represents a cell with a stone. Return the minimal number of moves necessary to reach the goal, or -1 if it is impossible.

 

Definition

    
Class:CornersGame
Method:countMoves
Parameters:String[]
Returns:int
Method signature:int countMoves(String[] board)
(be sure your method is public)
    
 

Constraints

-board will contain exactly 6 elements.
-Each element of board will contain exactly 6 characters.
-Each element of board will contain only the characters 'r', 's', and '.'.
-board will contain '.' characters at the initial and desired final positions of the draughts.
 

Examples

0)
    
{"......", 
 "......",
 "......",
 "......",
 "......",
 "......"}
Returns: 16
1)
    
{".....s",
 "..s.r.",
 "r.....",
 ".srs..",
 "..r...",
 "......"}
Returns: 19
The board shown on the picture above.
2)
    
{"......",
 "......",
 "....ss",
 "....ss",
 "...r..",
 "...r.."}
Returns: -1
We can not make any move.
3)
    
{"...s.r",
 "..r.s.",
 "rr.s..",
 "..s.rr",
 "s.rr..",
 ".s.s.."}
Returns: 54

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PartSorting

Greedy, Sorting



Used in:

SRM 307

Used as:

Division I Level One , Division II Level Two

Writer:

Mike Mirzayanov

Testers:

PabloGilberto , brett1479 , Olexiy , marian

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6447

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9987&pm=6447

Problem Statement

    You are given a int[] data. All elements in data are distinct. Only consecutive pairs of elements in data can be swapped. You are allowed to perform at most nSwaps swaps. Return the lexicographically maximal possible result.
 

Definition

    
Class:PartSorting
Method:process
Parameters:int[], int
Returns:int[]
Method signature:int[] process(int[] data, int nSwaps)
(be sure your method is public)
    
 

Notes

-Given two int[]s a and b of equal length, a is lexicographically greater than b if an index i (0 <= i < n) exists such that a[0] = b[0], a[1] = b[1], ..., a[i - 1] = b[i - 1] and a[i] > b[i], where n is the size of a.
 

Constraints

-data will contain between 1 and 50 elements, inclusive.
-Each element in data will be between 1 and 1000000, inclusive.
-All elements in data will be distinct.
-nSwaps will be between 0 and 1000000, inclusive.
 

Examples

0)
    
{10, 20, 30, 40, 50, 60, 70}
1
Returns: {20, 10, 30, 40, 50, 60, 70 }
Swap the first two elements.
1)
    
{3, 5, 1, 2, 4}
2
Returns: {5, 3, 2, 1, 4 }
First, swap the third and fourth elements, and then, swap the first and second elements.
2)
    
{19, 20, 17, 18, 15, 16, 13, 14, 11, 12}
5
Returns: {20, 19, 18, 17, 16, 15, 14, 13, 12, 11 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TourCounting

Advanced Math, Dynamic Programming, Graph Theory, Recursion



Used in:

SRM 306

Used as:

Division I Level Three

Writer:

soul-net

Testers:

PabloGilberto , brett1479 , Olexiy , lovro , Andrew_Lazarev

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6386

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9986&pm=6386

Problem Statement

    

You are given a directed graph g, and you must determine the number of distinct cycles in g that have length less than k. Since this number can be really big, return the answer modulo m. A cycle is a non-empty sequence of nodes (not necessarily distinct) in which there is an edge from each node to the next node, and an edge from the last node in the sequence to the first node. Two cycles are distinct if their sequences are not identical. See example 0 for further clarification.

g will be given as a String[] where the jth character of the ith element indicates whether there is an edge from node i to node j ('Y' means there is one, and 'N' means there is not).

 

Definition

    
Class:TourCounting
Method:countTours
Parameters:String[], int, int
Returns:int
Method signature:int countTours(String[] g, int k, int m)
(be sure your method is public)
    
 

Notes

-The answer modulo m means that you must return the remainder of dividing the result by m.
 

Constraints

-g will have between 1 and 35 elements, inclusive.
-Each element of g will have exactly N characters, where N is the number of elements in g.
-Each character of each element of g will be 'Y' or 'N'.
-The ith character of the ith element of g will be 'N'.
-k will be between 1 and 1000000 (106), inclusive.
-m will be between 1 and 1000000000 (109), inclusive.
 

Examples

0)
    
{"NYNY",
 "NNYN",
 "YNNN",
 "YNNN"}
6
100
Returns: 12

The possible cycles with length less than 6 are:

(0,3) ; (3,0) ; (0,1,2) ; (1,2,0) ; (2,0,1)

(0,3,0,3) ; (3,0,3,0) ; (0,1,2,0,3) ; (0,3,0,1,2)

(1,2,0,3,0) ; (2,0,3,0,1) ; (3,0,1,2,0)

Note that (0,3), (3,0) and (0,3,0,3) are all considered different.

1)
    
{"NYNNNNN",
 "NNYNNNN",
 "NNNYNNN",
 "NNNNYNN",
 "NNNNNYN",
 "NNNNNNY",
 "YNNNNNN"}
40
13
Returns: 9
All cycles have lengths that are multiples of 7. For each starting node and each multiple of 7 there exists one cycle. There are 5 non-zero multiples of 7 that are less than 40 (7,14,21,28,35) and 7 possible starting nodes. Therefore, the total number of cycles is 5x7=35. 35 modulo 13 is 9.
2)
    
{"NYNY",
 "NNNN",
 "YYNY",
 "NYNN"}
1000000
1000000000
Returns: 0
The graph does not have cycles.
3)
    
{"NY",
 "YN"}
1500
1
Returns: 0
Any number modulo 1 is zero.
4)
    
{"NYYNYYN",
 "YNYNYNY",
 "NYNYNYN",
 "YYYNYNY",
 "NNYYNNY",
 "NYYYNNY",
 "YYYYYYN"}
30
100
Returns: 72
5)
    
{"NYYY",
 "YNYY",
 "YYNY",
 "YNYN"}
1000
10000
Returns: 3564

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PartitionGraph



Used in:


Used as:



Writer:


Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6383

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10019&pm=6383

Problem Statement

    Given a simple undirected graph G, your task is to partition it into C disjoint sets of nodes. Your goal is to do this in such a way that as few edges are cut as possible, while each of the sets is relatively large. More specifically, you want to minimize the ratio: (edges cut)/(size of smallest set).



In order to receive any points on a test case, your ratio must be within 0.01% of the smallest ratio of any competitor. Assuming that you achieve this ratio, your score will be based on the time it takes you to find the answer. Your score for a test case will be inversely proportional to the time it takes plus 100 milliseconds, while your total score will simply be the sum of the scores for the test cases. Thus, if you have the smallest ratio on two cases with times 100 and 200 milliseconds, your score will be proportional to 1/(100+100)+1/(200+100).



The graphs will be generated as follows:
  1. C, the number of clusters (and input to you) will be chosen uniformly between 2 and 10, inclusive.
  2. N, the number of nodes in the graph will be chosen uniformly between 100 and 5,000, inclusive.
  3. p, the probability of an edge existing between nodes in different clusters, will be chosen uniformly between 0.05 and 0.25, inclusive.
  4. q, the probability of an edge between nodes in the same cluster, will be chosen uniformly between p+2*sqrt(p*C/N) and p+8*sqrt(p*C/N) (with the upper bound capped at 1).
  5. A graph is generated with N nodes, each node is in one of the C clusters with equal probability. Every undirected edge is then added with probability p or q depending on whether the edge is between different clusters or within one cluster.


For example, consider a graph with two clusters and 100 nodes, where nodes 0-49 are in cluster 0, while nodes 50-99 are in cluster 1. Imagine that p were chosen as 0.1, and q was chosen as 0.2. Then, for every pair of integers (i,j), if i and j were both in the same cluster (both 0-49 or both 50-99), there would be an edge between i and j with probability 0.2. If i and j were in different clusters, then the probability of an edge between i and j would be 0.1. Thus, in this case we would expect each node to have 49*0.2 edges to nodes in the same cluster, and 50*0.1 edges to nodes in the other cluster. If our algorithm found this parition, we would expect it to cut roughly 50*0.1*50=250 edges, and thus have a ratio of 250/50 = 5.



The graph will be given to you as two int[]'s: u and v. Corresponding elements of u and v represent a single undirected edge. For instance, there is an edge between u[0] and v[0]. The number of nodes are given as an input nodes. Your return should be a int[] with nodes elements. Element i of the return should represent the partition (out of C total) that node i is in. Everything is indexed from 0, including the return.
 

Definition

    
Class:PartitionGraph
Method:partition
Parameters:int[], int[], int, int
Returns:int[]
Method signature:int[] partition(int[] u, int[] v, int nodes, int C)
(be sure your method is public)
    
 

Notes

-The graph is undirected, so edges will only be listed once in the input.
-The time limit is 60 seconds.
-The memory limit is 1024 megabytes.
-A partition of nodes into C disjoint sets means that you should assign an integer between 0 and C-1 to every node.
-An edge is cut if its two end points are assigned different numbers (as described in the previous note).
-The scores you see for individual test cases encode the number of edges you cut and the size of your minimum partition. If the score is written down as an integer, the last 5 digits are your time, the 4 digits before them gives the size of your smallest partition, while the rest of the digits give the number of edges cut. For example, the score 1096 0012 00004 (spaces for clarity) indicates that your time was 4 milliseconds, your smallest cluster was 12 nodes, and you cut 1096 edges. This information will also appear in the "fatal errors" section for examples, though it is clearly not actually a fatal error.
-There are 20 non-example test cases. After the competition is over, all solutions will be re-run on a larger test set.
-The total scores will be normalized such that the highest score is exactly 10,000.
-The zip files for the examples contain one edge per line.
 

Constraints

-The graph will be generated as described above.
 

Examples

0)
    
"1"
Returns: 
"This graph has 100 nodes, and 9 clusters.  p = 0.1298495467416172, q = 0.562381664187069.  The input C=9 "
http://www.topcoder.com/contest/problem/PartitionGraph/test0.gz

The optimal ratio is less than 60.
1)
    
"2"
Returns: 
"This graph has 100 nodes, and 2 clusters.  p = 0.05512270939535211, q = 0.23170504638351752.  The input C=2 "
http://www.topcoder.com/contest/problem/PartitionGraph/test1.gz
2)
    
"3"
Returns: 
"This graph has 100 nodes, and 6 clusters.  p = 0.07393663470458767, q = 0.42640730225653994.  The input C=6 "
http://www.topcoder.com/contest/problem/PartitionGraph/test2.gz
3)
    
"1000"
Returns: 
"This graph has 2103 nodes, and 4 clusters.  p = 0.23752417679934573, q = 0.3425110757342353.  The input C=4 "
http://www.topcoder.com/contest/problem/PartitionGraph/test3.gz
4)
    
"1001"
Returns: 
"This graph has 4909 nodes, and 10 clusters.  p = 0.11841855221632161, q = 0.20495237307524405.  The input C=10 "
http://www.topcoder.com/contest/problem/PartitionGraph/test4.gz
5)
    
"1003"
Returns: 
"This graph has 3064 nodes, and 2 clusters.  p = 0.20617708771524107, q = 0.28020071025728954.  The input C=2 "
http://www.topcoder.com/contest/problem/PartitionGraph/test5.gz
6)
    
"1004"
Returns: 
"This graph has 390 nodes, and 10 clusters.  p = 0.06041993112425246, q = 0.2733661251252104.  The input C=10 "
http://www.topcoder.com/contest/problem/PartitionGraph/test6.gz
7)
    
"786008"
Returns: 
"This graph has 2789 nodes, and 4 clusters.  p = 0.16688716607823517, q = 0.2312691747743178.  The input C=4 "
http://www.topcoder.com/contest/problem/PartitionGraph/test7.gz
8)
    
"572968"
Returns: 
"This graph has 2953 nodes, and 2 clusters.  p = 0.1474143432742407, q = 0.18596635921872035.  The input C=2 "
http://www.topcoder.com/contest/problem/PartitionGraph/test8.gz
9)
    
"828700"
Returns: 
"This graph has 4324 nodes, and 9 clusters.  p = 0.20187512571848237, q = 0.2749548626937394.  The input C=9 "
http://www.topcoder.com/contest/problem/PartitionGraph/test9.gz

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RandomWalking

Graph Theory



Used in:

MM 1

Used as:

Division I Level One

Writer:

lars2520

Testers:

lbackstrom , tools

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6377

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10015&pm=6377

Problem Statement

    A random walk in a directed graph starts at some node in the graph and then follows one of that node's outgoing edges uniformly at random. The process is then repeated from the next node and so on. If a graph consists of a single strongly connected component, then a random walk will eventually visit every node in the graph. In this problem, your program will make a random walk of a graph. However, you will only be able to observe the in and out degrees of the vertices that you visit. Your task is to make as short a random walk as possible such that you have visited every node in the graph.



You should write two methods: init and walk. The init method will be called first with a single integer argument: the number of vertices in the graph. Subsequent calls will be made to the walk method and will give a sequences of in and out degree observations. Both of these methods should return an integer between 0 and one million, inclusive, indicating the number of steps your program wants to move at once. So, if you want to take 10 steps in the first iteration, your init method should return 10. Then, you will be given 10 degree observations in the next call to the walk method.



You are allowed to observe at most 10 sequences of degrees (walk will be called at most 10 times). Each time it will be given a int[] with 2 elements per observations. Element 2*i and 2*i+1 will given the in and out degrees of the ith observation, respectively. If you ever return 0, it will be assumed that you are done and want to make no further observations.



Scoring will be based on two factors: the number of nodes that you visit before quiting, and the total number of observations you make. In the best case, you will stop as soon as you hit the last unvisited node, in which case you will get 100 points. If you don't visit all the nodes, you will lose half your points for each unvisited nodes, so your score will be 100*0.5unvisited. If you visit all the nodes and make some additional observations, your score will be 100-(percent extra observations)/3 (with a minimum of 0). For example, if you visited all but 2 nodes, you would get 25 points. If you visisted the last node on observation 100, but you made a total of 130 observations, you would receive 90 points (having made 30% extra observations). Your total score will simply be the sum of your individual scores.



The graphs will be generated via a very simple model. First, the number of nodes will be selected between 10 and 100, inclusive, with size K chosen with probability proportional to 1/K. Then, a probability, p is chosen between 0 and 10/K. For each potential edge (u,v) (where u does not equal v), that edge is added with probability p. If the generated graph has a single strongly connected component, it is kept, otherwise, p and all the edges are regenerated (the size is kept), and the process is repeated until a graph with a single strong component is generated.
 

Definition

    
Class:RandomWalking
Method:init
Parameters:int
Returns:int
Method signature:int init(int nodes)
 
Method:walk
Parameters:int[]
Returns:int
Method signature:int walk(int[] seq)
(be sure your methods are public)
    
 

Notes

-You will have a total of 20 seconds execution time (not 20 seconds per sequence).
-The memory limit is 64 MB.
-There are 100 test cases.
-Graphs are given as adjacency lists. For instance, in example 0, there are edges from node 0 to nodes 1, 2 and 9.
-The return from the 10th call to walk is ignored (treated as if it is 0).
-The calls to walk form a single continuous random walk. In other words, concatenating all of the inputs to the walk methods gives a continuous walk.
 

Examples

0)
    
"1"
Returns: 
"0: 1 2 9 
1: 0 4 5 6 7 
2: 3 8 9 
3: 2 5 9 
4: 0 2 3 6 7 8 
5: 8 
6: 3 4 5 7 9 
7: 1 4 6 8 9 
8: 1 3 7 
9: 0 1 2 5 7 
"
1)
    
"2"
Returns: 
"0: 4 5 7 8 9 
1: 0 3 4 5 6 7 8 9 
2: 0 1 3 4 5 6 7 9 
3: 0 1 2 4 5 6 7 8 9 
4: 1 3 5 6 8 9 
5: 0 1 2 3 4 6 7 8 9 
6: 1 2 3 4 7 8 9 
7: 0 1 2 3 5 6 8 9 
8: 1 2 3 4 5 7 9 
9: 0 2 3 4 6 8 
"
2)
    
"50"
Returns: 
"0: 19 28 41 43 45 46 48 
1: 4 11 15 17 19 25 26 34 39 40 44 47 
2: 3 9 12 16 31 34 40 43 46 
3: 2 5 13 16 25 28 30 32 35 38 40 44 
4: 6 14 18 22 31 35 47 
5: 2 4 14 16 20 26 27 37 
6: 0 5 12 14 16 21 25 27 33 36 37 44 47 
7: 0 31 32 36 37 43 44 
8: 0 10 17 23 27 29 31 32 33 35 37 40 45 47 
9: 2 3 10 11 14 15 16 32 38 48 
10: 6 8 12 23 37 44 48 
11: 8 9 10 17 19 20 34 48 
12: 1 2 13 20 22 30 31 33 39 41 45 
13: 1 6 9 19 33 36 41 45 
14: 6 20 22 25 31 37 41 43 49 
15: 3 8 9 21 24 33 39 
16: 6 12 22 23 24 26 27 29 36 38 39 44 
17: 5 9 13 21 23 24 27 34 39 42 43 45 49 
18: 9 10 14 20 22 24 25 26 29 31 32 35 44 
19: 12 16 20 22 23 25 28 34 35 46 
20: 0 1 2 3 7 11 18 21 25 27 44 45 49 
21: 3 4 7 9 10 14 23 28 33 37 42 48 49 
22: 1 7 12 19 21 26 30 40 43 44 
23: 0 3 4 5 8 9 11 14 27 30 38 41 43 45 49 
24: 5 6 8 11 15 16 23 30 32 34 35 36 37 42 
25: 0 8 16 18 19 31 33 34 46 
26: 0 11 13 27 33 35 40 45 49 
27: 7 11 21 23 38 39 40 
28: 0 7 8 9 24 27 30 31 33 41 44 
29: 6 7 9 12 18 19 26 30 32 34 38 41 47 
30: 1 4 7 14 18 22 23 26 29 31 32 44 45 47 
31: 0 4 11 14 18 22 29 30 37 45 
32: 9 13 17 20 21 24 26 28 29 30 35 42 
33: 6 8 9 14 16 21 22 24 25 28 30 37 40 42 45 47 
34: 7 21 29 36 43 
35: 11 15 18 41 43 46 
36: 9 25 28 48 
37: 0 7 10 18 28 38 42 
38: 3 4 12 13 15 17 18 23 27 35 
39: 1 19 35 37 47 
40: 9 16 18 29 38 42 
41: 2 3 15 16 17 22 25 32 36 37 40 42 45 
42: 2 9 15 16 23 28 30 34 
43: 0 8 22 23 27 29 33 37 45 46 
44: 2 18 30 42 47 48 
45: 0 8 12 26 32 34 40 
46: 7 9 18 23 24 25 30 33 36 37 40 
47: 11 12 13 14 19 29 36 44 48 
48: 15 23 25 33 38 
49: 12 18 22 25 26 42 43 
"
3)
    
"100"
Returns: 
"0: 1 6 7 10 11 14 17 18 19 20 24 25 
1: 0 2 3 4 6 7 8 17 23 25 
2: 0 3 4 5 6 11 16 19 21 24 
3: 0 2 10 13 14 15 16 18 20 23 
4: 0 3 10 13 14 15 18 20 21 22 23 25 
5: 6 8 11 12 14 15 16 17 
6: 0 3 5 8 9 10 11 12 16 19 20 22 23 
7: 1 17 18 20 23 
8: 1 4 5 7 12 13 15 17 20 22 
9: 1 4 5 6 8 11 12 17 19 21 22 
10: 1 5 7 9 11 14 16 18 19 
11: 0 4 6 9 10 18 21 24 
12: 2 3 5 7 8 9 10 11 17 19 20 
13: 1 7 8 9 12 22 24 
14: 1 4 7 8 9 16 17 21 
15: 1 7 10 12 16 18 19 22 
16: 1 13 14 15 21 22 
17: 0 2 4 14 15 18 
18: 0 3 4 12 16 17 19 22 23 24 
19: 0 1 4 7 8 9 10 11 12 20 21 22 24 
20: 2 3 4 5 6 7 9 10 12 13 16 17 19 22 24 25 
21: 0 1 6 7 8 9 14 20 25 
22: 3 4 5 6 7 10 11 17 
23: 2 4 5 6 8 12 16 18 20 24 25 
24: 0 9 11 13 14 17 18 25 
25: 0 1 6 7 9 15 21 23 24 
"
4)
    
"73380160"
Returns: 
"0: 1 2 3 4 5 6 7 8 9 10 
1: 0 2 4 5 8 10 
2: 0 3 4 5 6 7 8 10 
3: 0 1 2 4 5 6 7 8 10 
4: 0 1 2 3 6 7 8 10 
5: 0 1 2 3 6 8 9 10 
6: 0 1 2 3 4 7 8 9 10 
7: 0 1 2 3 4 8 9 10 
8: 1 3 4 6 7 9 10 
9: 0 1 2 3 4 5 7 8 10 
10: 0 1 2 3 5 8 9 
"
5)
    
"499769812"
Returns: 
"0: 5 22 25 28 63 
1: 13 24 26 43 58 61 
2: 5 9 14 17 20 23 26 40 50 
3: 9 27 35 37 38 49 54 57 
4: 29 44 45 62 
5: 9 44 48 62 63 
6: 9 18 31 43 46 61 65 
7: 0 12 19 25 34 39 
8: 9 17 21 44 53 62 63 
9: 0 3 5 17 27 44 53 
10: 7 16 24 37 38 56 67 
11: 3 4 13 15 32 50 64 
12: 1 7 14 20 28 29 30 32 52 59 60 65 
13: 2 4 34 44 51 57 
14: 8 23 28 36 53 54 55 62 63 65 
15: 1 6 27 30 48 55 57 
16: 2 10 26 47 53 61 66 
17: 5 8 11 24 30 41 42 50 59 
18: 0 6 11 33 35 44 52 59 68 
19: 6 41 49 55 
20: 18 25 36 39 48 58 
21: 1 4 19 27 30 35 43 47 48 
22: 11 15 32 41 58 62 66 
23: 5 17 18 20 21 34 35 43 
24: 0 5 37 50 51 61 62 63 
25: 7 15 21 36 
26: 8 10 20 36 41 43 56 
27: 3 12 14 34 38 51 55 59 63 64 66 
28: 3 15 26 49 56 
29: 2 9 22 35 41 44 46 49 59 63 
30: 28 32 40 41 
31: 5 9 27 49 52 55 56 
32: 2 5 33 41 55 57 59 63 
33: 26 38 51 63 66 
34: 14 41 42 
35: 7 10 28 31 57 67 
36: 2 13 19 50 
37: 6 13 14 41 47 49 54 60 63 
38: 6 22 39 
39: 9 13 16 22 48 58 
40: 8 25 28 47 59 
41: 0 8 18 25 38 46 53 60 61 62 
42: 13 18 33 39 56 60 65 
43: 2 5 13 14 27 34 57 
44: 8 11 17 25 27 37 
45: 16 36 38 48 50 56 59 64 65 
46: 1 3 8 14 16 19 24 50 64 
47: 14 25 32 40 60 67 
48: 3 10 18 32 35 50 56 61 
49: 8 20 25 29 43 54 
50: 12 13 14 16 31 33 34 47 49 57 58 61 
51: 24 36 46 61 62 
52: 33 35 38 41 44 48 64 
53: 5 12 13 24 28 40 
54: 3 22 34 42 45 65 
55: 1 9 10 15 16 31 36 38 61 67 
56: 4 6 9 32 38 54 59 67 
57: 5 13 16 23 24 25 29 35 36 41 46 54 65 
58: 13 18 23 26 33 34 57 60 61 
59: 0 4 14 19 35 37 42 47 54 65 
60: 8 18 21 24 53 66 
61: 0 3 11 13 19 22 51 62 
62: 4 8 20 28 48 49 50 54 
63: 2 3 28 35 39 51 52 53 64 68 
64: 13 21 36 46 55 
65: 3 6 14 29 36 43 50 55 
66: 19 20 25 54 55 56 59 
67: 3 5 7 17 19 22 48 54 59 
68: 2 8 20 23 31 48 
"
6)
    
"78736497"
Returns: 
"0: 1 19 24 32 
1: 7 13 20 27 
2: 3 5 29 
3: 6 16 28 29 30 
4: 6 
5: 11 14 16 17 22 31 
6: 1 2 8 31 
7: 29 30 
8: 4 10 12 19 
9: 15 22 
10: 0 12 13 18 29 
11: 2 7 17 20 
12: 11 13 20 27 29 
13: 3 5 6 11 23 
14: 21 25 27 28 
15: 11 24 25 31 
16: 1 29 
17: 5 9 28 
18: 1 6 29 
19: 5 6 24 26 
20: 0 5 12 17 30 31 
21: 14 20 30 
22: 1 15 19 20 26 30 
23: 6 8 13 26 28 
24: 0 13 14 16 20 
25: 3 23 31 
26: 14 20 23 24 
27: 3 15 20 23 30 
28: 1 10 12 22 29 31 
29: 9 18 28 31 32 
30: 27 
31: 5 16 24 30 
32: 26 28 30 31 
"
7)
    
"880114950"
Returns: 
"0: 3 4 7 10 11 13 15 
1: 2 3 5 8 9 13 17 
2: 4 5 8 9 17 
3: 6 9 12 
4: 3 5 6 10 11 13 15 17 
5: 0 2 3 6 7 11 13 16 
6: 1 2 3 4 8 10 11 13 14 15 17 
7: 0 1 2 3 9 12 13 15 16 
8: 0 5 7 14 
9: 0 3 5 6 7 8 10 13 17 
10: 0 1 2 3 5 6 8 14 15 16 
11: 0 1 4 12 16 17 
12: 1 2 3 5 6 9 11 
13: 3 5 7 8 14 15 16 17 
14: 2 3 4 7 11 12 13 16 
15: 1 2 4 6 7 8 10 12 13 
16: 0 5 6 8 10 12 13 14 
17: 2 5 7 8 13 
"
8)
    
"347340626"
Returns: 
"0: 1 2 5 6 7 9 10 11 
1: 4 6 10 
2: 5 6 8 10 
3: 4 5 7 9 
4: 5 7 8 9 11 
5: 0 1 3 7 9 10 
6: 2 3 4 5 8 11 
7: 1 4 6 9 10 
8: 4 6 9 11 
9: 2 8 11 
10: 0 1 2 3 6 8 
11: 6 
"
9)
    
"866165179"
Returns: 
"0: 1 7 12 13 18 19 38 45 
1: 5 6 12 14 21 26 31 35 38 43 44 
2: 4 5 6 16 17 27 33 36 43 
3: 7 8 9 16 23 28 29 30 46 
4: 3 7 17 23 28 31 32 35 36 37 38 39 46 
5: 1 4 13 14 15 17 18 31 33 41 
6: 2 7 14 15 18 29 30 34 38 42 44 
7: 2 10 11 12 16 18 19 35 45 
8: 16 18 19 28 38 47 
9: 3 18 21 37 38 39 41 46 
10: 0 3 5 7 9 19 23 27 29 33 34 38 
11: 5 20 22 36 38 39 41 
12: 4 10 16 17 26 33 37 
13: 1 3 6 7 11 21 22 25 26 30 31 32 34 36 37 44 
14: 1 5 7 8 12 16 18 30 31 32 40 41 42 
15: 2 10 14 20 25 35 40 
16: 8 12 14 15 20 21 25 26 35 36 
17: 2 12 14 15 20 26 28 29 32 
18: 5 8 9 13 14 17 19 23 26 27 38 
19: 7 16 17 28 29 35 36 39 40 42 45 
20: 1 6 9 12 13 27 29 33 39 47 
21: 15 23 26 33 41 44 
22: 10 12 21 32 35 36 39 41 42 45 
23: 0 4 7 10 24 28 32 36 38 41 47 
24: 6 8 10 12 14 16 18 21 29 32 33 39 41 
25: 0 9 16 21 24 27 36 37 38 
26: 2 10 14 16 17 22 33 34 37 43 45 
27: 4 10 11 18 23 28 34 35 36 39 41 43 
28: 8 9 13 15 22 24 25 26 30 35 40 
29: 5 9 24 26 31 33 46 
30: 7 9 13 17 21 41 
31: 4 9 14 15 23 24 40 
32: 5 9 10 11 16 17 18 24 37 40 41 43 
33: 2 6 7 16 21 25 39 42 44 46 
34: 1 2 5 8 10 11 14 20 28 32 35 40 46 
35: 1 10 13 15 16 24 40 41 
36: 3 8 10 14 15 17 26 30 40 41 45 46 
37: 1 4 17 22 23 25 26 28 29 39 43 
38: 2 5 23 24 27 28 31 45 
39: 1 3 7 16 17 34 41 46 
40: 1 14 20 24 29 33 38 44 
41: 2 6 12 23 31 34 40 42 47 
42: 1 2 12 15 29 30 38 39 47 
43: 9 12 31 38 
44: 3 5 7 10 20 35 36 37 40 46 
45: 1 4 6 17 21 23 25 30 31 34 40 42 46 
46: 4 5 7 11 13 23 29 31 34 41 
47: 4 8 9 14 17 21 32 36 38 44 45 
"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Wizarding

Brute Force, Recursion



Used in:

TCHS SRM 2

Used as:

Division I Level Three

Writer:

ivankovic

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6250

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10024&pm=6250

Problem Statement

    A spell is defined by its incantation, the word spoken when the spell is being cast. If you know the incantation of a spell, you can create counterspells in the following manner. First, you can optionally delete any number of characters from the original incantation. Note that empty incantations are not valid so you cannot delete all characters. Then, you can replace any number of the remaining characters according to a set of replacement rules. The replacement rules tell you which letters can be replaced, and the letters with which they can be replaced. For example, if the original incantation is "AA" and the allowed replacement is 'A' to 'Z', the following counterspells are possible: "AA", "A", "Z", "ZZ", "AZ", "ZA".



The best counterspell is the one with the greatest power. The power of a spell is the product of all its character values modulo 77077, where the value for a character is its position in the alphabet (character 'A' has value 1, character 'B' value 2, character 'C' value 3, and so on). The best possible counterspell for "AA" in the example above is "ZZ", which has a power of 676.



Please note that if the allowed replacements are 'A' to 'B' and 'B' to 'C', the counterspell for "AB" is "BC" not "CC". You cannot change a character that has already been changed, even if it would lead to a more powerful spell.



You will be given a String spell, the incantation of the spell you are going to counter, and a String rules, the allowed replacements for letters. The first character in rules is the allowed replacement for the letter 'A', the second for 'B' and so on. The character '-' is used to denote a letter that cannot be replaced. Your program must return a String, the most powerful counterspell available. If multiple return values are possible, return the shortest among them. If a tie still exists return the lexicographically earliest.
 

Definition

    
Class:Wizarding
Method:counterspell
Parameters:String, String
Returns:String
Method signature:String counterspell(String spell, String rules)
(be sure your method is public)
    
 

Constraints

-spell will contain between 1 and 13 characters, inclusive.
-spell will contain only uppercase letters ('A'-'Z').
-rules will contain exactly 26 characters.
-rules will contain only uppercase letters ('A'-'Z') and dashes ('-').
 

Examples

0)
    
"AA"
"Z-------------------------"
Returns: "ZZ"
The example from the problem statement.
1)
    
"AB"
"ZS------------------------"
Returns: "ZS"
The possible counterspells are "AB", "A", "B", "Z", "S", "ZB", "AS" and "ZS".

"ZS" is the most powerful.
2)
    
"ZZZZ"
"-------------------------Z"
Returns: "ZZZZ"
3)
    
"ABCDE"
"ZYXXYXZZXYXXZZXZYYXZZZX---"
Returns: "ZXXE"
4)
    
"ABCDEABCDEABC"
"ACBDESKADSLOEDDDASDBADEDAE"
Returns: "CCDECCECC"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

EscapingJail

Dynamic Programming, Graph Theory



Used in:

SRM 301

Used as:

Division I Level Two

Writer:

soul-net

Testers:

PabloGilberto , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6222

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9822&pm=6222

Problem Statement

    

In a jail, some pairs of prisoners are chained together to make it more difficult for them to escape. A group of rebels has decided to escape, and one important part of their plan involves pressing two distant buttons simultaneously. They must determine the two prisoners best suited for this task.

Given the configuration of chains between prisoners, return the maximum distance that can be achieved between two prisoners. If there is no limit to that distance, return -1. You will be given a String[] chain, where the ith character of the jth element represents the length of the chain between prisoners i and j:

'0'-'9': Distances 0 to 9 feet, in order.

'a'-'z': Distances 10 to 35 feet, in order.

'A'-'Z': Distances 36 to 61 feet, in order.

' ': Space means there is no chain between that pair of prisoners.

 

Definition

    
Class:EscapingJail
Method:getMaxDistance
Parameters:String[]
Returns:int
Method signature:int getMaxDistance(String[] chain)
(be sure your method is public)
    
 

Constraints

-chain will have between 2 and 50 elements, inclusive.
-Each element of chain will have exactly N characters, where N is the number of elements of chain.
-Character i of element j of chain and character j of element i of chain will be equal.
-Character i of element i of chain will be '0'.
-Each character of each element of chain will be a digit ('0'-'9'), an uppercase letter ('A'-'Z'), a lowercase letter ('a'-'z') or a space ' '.
 

Examples

0)
    
{"0568",
 "5094",
 "6903",
 "8430"}
Returns: 8
Prisoners 1 and 2 are chained with length 9. However, they are both also chained to prisoner 3 with chains of length 3 and 4 respectively, so they cannot stand more than 7 feet apart. Prisoners 0 and 3, on the other hand, can stand 8 feet apart without trouble.
1)
    
{"0 ",
 " 0"}
Returns: -1
Both prisoners are completely unchained, so there is no limit to the distance they can achieve.
2)
    
{"0AxHH190",
 "A00f3AAA",
 "x00     ",
 "Hf 0  x ",
 "H3  0   ",
 "1A   0  ",
 "9A x  0Z",
 "0A    Z0"}
Returns: 43
3)
    
{"00",
 "00"}
Returns: 0
They are not going too far.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

JoinedString

Dynamic Programming, String Manipulation



Used in:

SRM 302

Used as:

Division I Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , legakis , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6215

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9823&pm=6215

Problem Statement

    You are given a String[] words. Return the shortest String that contains all the words as substrings. If there are several possible answers, return the one that comes first lexicographically.
 

Definition

    
Class:JoinedString
Method:joinWords
Parameters:String[]
Returns:String
Method signature:String joinWords(String[] words)
(be sure your method is public)
    
 

Constraints

-words will contain between 1 and 12 elements, inclusive.
-Each element of words will contain between 1 and 50 characters, inclusive.
-Each element of words will consist of only uppercase letters ('A'-'Z').
 

Examples

0)
    
{"BAB", "ABA"}
Returns: "ABAB"
There are two strings of length 4 that contain both given words: "ABAB" and "BABA". "ABAB" comes earlier lexicographically.
1)
    
{"ABABA", "AKAKA", "AKABAS", "ABAKA"}
Returns: "ABABAKAKABAS"
2)
    
{"AAA","BBB", "CCC", "ABC", "BCA", "CAB"}
Returns: "AAABBBCABCCC"
3)
    
{"OFG", "SDOFGJTILM", "KBWNF", "YAAPO", "AWX", "VSEAWX", "DOFGJTIL", "YAA"}
Returns: "KBWNFSDOFGJTILMVSEAWXYAAPO"
4)
    
{"NVCSKFLNVS", "HUFSPMRI", "FLNV", "KMQD", "RPJK", "NVSQORP", "UFSPMR", "AIHUFSPMRI"}
Returns: "AIHUFSPMRINVCSKFLNVSQORPJKMQD"
5)
    
{"STRING", "RING"}
Returns: "STRING"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FactCount

Graph Theory



Used in:

TCO06 Semi 2

Used as:

Division I Level Two

Writer:

dgoodman

Testers:

PabloGilberto , lbackstrom , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6201

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9981&pm=6201

Problem Statement

    Given a collection of facts, we would like to get rid of as much redundancy as possible. The facts involved in this problem are members of a transitive relation between uppercase letters. So each fact is a pair of uppercase letters such as AB meaning that A is related to B. A letter may or may not be related to itself, but transitivity holds: if A is related to B and B is related to C then we can infer that A is related to C.

Create a class FactCount that contains a method minFacts that is given a String[] known and that returns the size of the smallest set of facts that will allow us to infer everything (and only those things) that can be inferred from the facts contained in known.

Each element of known will contain 1 or more facts separated by a single space. The smallest set of facts may contain facts that can be inferred from known but that are not contained in it.

 

Definition

    
Class:FactCount
Method:minFacts
Parameters:String[]
Returns:int
Method signature:int minFacts(String[] known)
(be sure your method is public)
    
 

Constraints

-known will contain between 1 and 50 elements, inclusive.
-Each element of known will contain between 2 and 50 characters, inclusive.
-Each element of known will consist of pairs of uppercase letters ('A'-'Z'), separated by a space (' ').
 

Examples

0)
    
{"AA AA AA AB"}
Returns: 2
AA and AB capture all the content of the 4 facts in known.
1)
    
{"AB AC CA AA BC", "AD"}
Returns: 4
AB, CA, BC, and AD allow us to infer both AA (AB, BC, CA gives AA by transitivity) and AC (AB, BC gives AC by transitivity), and there is no smaller subset that allows us to infer all the known facts.
2)
    
{"AB BA BC CB"}
Returns: 3
The set {AC,BA,CB} allows us to infer exactly the same facts. Note that AC is not a fact contained in known, but these 3 facts allow us to infer exactly the same things that we can infer from the 4 facts contained in known.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DivisorInc

Graph Theory, Math



Used in:

SRM 302

Used as:

Division I Level One , Division II Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , legakis , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6186

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9823&pm=6186

Problem Statement

    

There is an integer K. You are allowed to add to K any of its divisors not equal to 1 and K. The same operation can be applied to the resulting number and so on. Notice that starting from the number 4, we can reach any composite number by applying several such operations. For example, the number 24 can be reached starting from 4 using 5 operations: 4->6->8->12->18->24.

You will solve a more general problem. Given ints N and M, return the minimal number of the described operations necessary to transform N into M. Return -1 if M can't be obtained from N.

 

Definition

    
Class:DivisorInc
Method:countOperations
Parameters:int, int
Returns:int
Method signature:int countOperations(int N, int M)
(be sure your method is public)
    
 

Constraints

-N will be between 4 and 100000, inclusive.
-M will be between N and 100000, inclusive.
 

Examples

0)
    
4
24
Returns: 5
The example from the problem statement.
1)
    
4
576
Returns: 14
The shortest order of operations is: 4->6->8->12->18->27->36->54->81->108->162->243->324->432->576.
2)
    
8748
83462
Returns: 10
The shortest order of operations is: 8748->13122->19683->26244->39366->59049->78732->83106->83448->83460->83462.
3)
    
235
98234
Returns: 21
4)
    
4
99991
Returns: -1
The number 99991 can't be obtained because it is prime.
5)
    
82736
82736
Returns: 0
We don't need any operations. N and M are already equal.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SymmetricalTree

Dynamic Programming



Used in:

TCO06 Semi 1

Used as:

Division I Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , lbackstrom , brett1479 , radeye , Olexiy , marian

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6185

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9980&pm=6185

Problem Statement

    

Consider the following code, which traverses a tree and prints a sequence of characters:

    bypass(Node v) {
        for i=0..size(v.children)-1 {
            write('1');
            bypass(v.children[i]);
            write('0');
        }
    }

Starting from the root this code will generate a string of 0's and 1's that fully describes a tree. For example, "1101100110011000" will represent the tree in the following picture (nodes are marked in the order of traversal).

A tree is called symmetrical if, after reversing the order of children for all nodes, the string representation of the tree is not changed. For example, the tree in the picture is not symmetrical because the string representation changes to "1110011001100100" after the order of children is reversed for all nodes.

You will be given a String tree. You are to make it symmetrical by removing some nodes and changing the order of children for some nodes. You can remove a node only if all its children are removed too. You should return tree after making it symmetrical. If there are multiple ways to make tree symmetrical, you should minimize the number of removed nodes. If two or more solutions still remain, return the one that comes first lexicographically.

 

Definition

    
Class:SymmetricalTree
Method:makeSymmetrical
Parameters:String
Returns:String
Method signature:String makeSymmetrical(String tree)
(be sure your method is public)
    
 

Constraints

-tree will contain between 1 and 40 characters, inclusive.
-tree will only contain the digits '0' and '1'.
-tree will represent a valid tree.
 

Examples

0)
    
"1101100110011000"
Returns: "11011001100100"
This is the example from the problem statement. We should remove the 9th node (see picture).
1)
    
"10101100"
Returns: "10110010"
We can make the tree symmetrical by using only rearrangements.
2)
    
"1011100100"
Returns: "110100"
3)
    
"101101100110101000"
Returns: "11011010100100"
4)
    
"11010010110110010101100010110100"
Returns: "10110100110110010110010011010010"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

IndicatorMotionDrawing

Dynamic Programming, Graph Theory, Simulation



Used in:

SRM 298

Used as:

Division II Level Three

Writer:

soul-net

Testers:

PabloGilberto , brett1479 , radeye , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6183

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9819&pm=6183

Problem Statement

    In this problem, you will write a program that controls the actions of a progress indicator. The indicator is a single bar character with one of 4 states: '|', '-', '\', and '/'. The program consists of a sequence of instructions, where each instruction is one of 7 possible actions:
  • 'L': Spin left. If the bar is in state '|', it goes to '\'. State '\' goes to '-', '-' goes to '/', and '/' goes to '|'.
  • 'R': Spin right. This is the exact opposite of 'L': '\' goes to '|', '|' goes to '/', '/' goes to '-', and '-' goes to '\'.
  • 'F': Flip. The bar is rotated 90 degrees: '\' becomes '/', '/' becomes '\', '-' becomes '|', and '|' becomes '-'.
  • 'U': The bar moves up.
  • 'D': The bar moves down.
  • '<': The bar moves left.
  • '>': The bar moves right.
Each instruction requires one second to complete. The computer's screen refresh is broken, so whenever the bar moves to a new location, its state at the previous location remains visible and the new location is overwritten with the bar's current state (see examples for clarification). To take advantage of this unexpected "feature", you've decided to come up with a game.

Initially, the bar is at (0, 0), which is the upper-left corner of the screen, and it is in state startState. The rest of the screen is empty. You are given a String[] with a desiredScreen that is your target. You must construct a program that will end with the screen looking exactly like desiredScreen.

For example, if your desiredScreen is

{"///",
 "///",
 "---"}
and your startState is '-', you can achieve that with "L>>D<<DR>>". In this case, it took 10 seconds to get the screen to desiredScreen.



For the given desiredScreen and startState, return the minimum time needed to achieve this goal, or -1 if it is impossible to do so.
 

Definition

    
Class:IndicatorMotionDrawing
Method:getMinSteps
Parameters:String[], char
Returns:int
Method signature:int getMinSteps(String[] desiredState, char startState)
(be sure your method is public)
    
 

Notes

-The bar cannot be moved outside the boundary of desiredScreen.
-Note that desiredScreen may contain spaces. The bar can never pass through a cell which has a space in desiredScreen because it would leave a character that would never be erased.
-In the examples the character '\' appears as '\\' because of the C++/Java syntax for escaping characters.
 

Constraints

-startState will be one of '/', '\', '|', or '-'.
-desiredScreen will have between 1 and 3 elements, inclusive.
-Each element of desiredScreen will contain exactly N characters, where N is an integer between 1 and 4, inclusive.
-Each character of each element of desiredScreen will be one of ' ', '/', '\', '|', or '-'.
 

Examples

0)
    
{"///",
 "///",
 "---"}
'-'
Returns: 10
The example from the problem statement.
1)
    
{" ||",
 "|||",
 "|||"}
'|'
Returns: -1
Since the bar is initially at (0,0), it's impossible to achieve a desiredScreen that has a space at that location.
2)
    
{"/- ",
 "/  ",
 "/--"}
'/'
Returns: 9
Don't step on spaces!

Here, you are forced to step twice at least in (0,0). One way to achieve the best time is "R><LDD>R>".

This will lead to this sequence of screens, with dots representing spaces and and the location of the bar written below each screen as (row,column):

 /..      -..      --.      --.      /-.      /-.      /-.      /-.      /-.      /-.
 ...  ->  ...  ->  ...  ->  ...  ->  ...  ->  /..  ->  /..  ->  /..  ->  /..  ->  /..
 ...      ...      ...      ...      ...      ...      /..      //.      /-.      /--
(0,0)    (0,0)    (0,1)    (0,0)    (0,0)    (1,0)    (2,0)    (2,1)    (2,1)    (2,2)
3)
    
{"/-|/",
 "/ |/",
 "-/\\/"}
'\\'
Returns: 18

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

JobPlanner

Graph Theory



Used in:

TCCC07 Round 2

Used as:

Division I Level Three

Writer:

andrewzta

Testers:

PabloGilberto , brett1479 , radeye , Olexiy , ivan_metelsky

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6177

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10891&pm=6177

Problem Statement

    

You have m workers numbered 1 through m, and you have n tasks that must be completed. You know which tasks can be performed by each of the workers. If worker i completes t different tasks, he must be paid cost[i]*t2. You would like to minimize the total cost of completing all the tasks.

You will be given a String[] can describing the capabilities of your workers. The i-th element describes worker i and contains n characters. The j-th character is 'Y' if the worker can perform the j-th task, and 'N' if he can't. You will also be given a int[] cost. The i-th element of cost is the cost of worker i (as used in the formula above). All indices are 1-based. Return the minimal total cost required to complete all the tasks, or -1 if all the tasks cannot be completed.

 

Definition

    
Class:JobPlanner
Method:minimalCost
Parameters:String[], int[]
Returns:int
Method signature:int minimalCost(String[] can, int[] cost)
(be sure your method is public)
    
 

Constraints

-can will contain between 1 and 50 elements, inclusive.
-All elements of can will contain the same number of characters.
-Each element of can will contain between 1 and 50 characters, inclusive.
-Each element of can will contain only 'Y' and 'N' characters.
-cost will contain the same number of elements as can.
-Each element of cost will be between 1 and 500,000, inclusive.
 

Examples

0)
    
{"YY","YY"}
{1,2}
Returns: 3
In this case each worker can perform any task. It is better to give one task to the first worker, and another task to the second worker. The total cost is 1 * 12 + 2 * 12 = 3.
1)
    
{"YY","YY"}
{1,5}
Returns: 4
In this case it is better to give both tasks to the first worker since the second one is too expensive. The total cost is 1 * 22 + 5 * 02 = 4.
2)
    
{"YN", "YY"}
{1, 5}
Returns: 6
In this case the first worker cannot perform the second task, so we need to use the second worker. The total cost is 1 * 12 + 5 * 12 = 6.
3)
    
{"YN", "YN"}
{1, 1}
Returns: -1
In this case the second task cannot be completed at all.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LadderPermutation

Greedy, Search



Used in:

SRM 332

Used as:

Division I Level Three

Writer:

andrewzta

Testers:

PabloGilberto , brett1479 , Cosmin.ro , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6175

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10012&pm=6175

Problem Statement

    

You have n distinct integers between 1 and n, inclusive. A permutation of these integers is called an (m,k)-ladder permutation if its longest increasing subsequence has length m and its longest decreasing subsequence has length k. A subsequence is a sequence created by removing zero or more elements from an original sequence. The relative order of the remaining elements must be preserved. For example, {1, 3} is a subsequence of {1, 2, 3}, but {3, 2} is not. An increasing sequence is one in which each element is greater than the previous element, and a decreasing sequence is one in which each element is less than the previous element.

You are given ints n, m and k. Return a int[] containing the (m,k)-ladder permutation of size n. If there are multiple possibilities, return the one that comes first lexicographically. If there is no such permutation, return an empty int[]. Sequence A comes before sequence B lexicographically if A contains a lower value at the first position where they differ.

 

Definition

    
Class:LadderPermutation
Method:createLadder
Parameters:int, int, int
Returns:int[]
Method signature:int[] createLadder(int n, int m, int k)
(be sure your method is public)
    
 

Constraints

-n will be between 1 and 50, inclusive.
-m will be between 1 and n, inclusive.
-k will be between 1 and n, inclusive.
 

Examples

0)
    
4
2
2
Returns: {2, 1, 4, 3 }
In this case, all longest increasing subsequences have length 2 (for example, {1, 3}), and all longest decreasing subsequences have length 2 (for example, {2, 1}).
1)
    
3
2
2
Returns: {1, 3, 2 }
2)
    
2
1
1
Returns: { }
In this case, the two numbers will always form an increasing or decreasing sequence of length 2. There is no permutation where the longest increasing/decreasing subsequence only has length 1.
3)
    
6
3
2
Returns: {2, 1, 4, 3, 6, 5 }
4)
    
6
2
3
Returns: {3, 2, 1, 6, 5, 4 }
5)
    
7
4
4
Returns: {1, 2, 3, 7, 6, 5, 4 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

IndicatorMotionReverse

Greedy, Simulation



Used in:

SRM 301

Used as:

Division I Level One , Division II Level Two

Writer:

soul-net

Testers:

PabloGilberto , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6172

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9822&pm=6172

Problem Statement

    

The first thing you have to do is to concatenate all elements of actions into one long string, and that will be your input string.

In this problem, you will write a program that controls the actions of a progress indicator. The indicator is a single bar character in the middle of the screen with one of 4 states: '|', '/', '-', and '\'. From now on, we will refer to '\' as 'N', for programming convenience. The program is a sequence of instructions in the form:

<instr> <secs>

where <instr> represents one of 4 possible actions, and <secs> is the action's duration in seconds. The action is performed once each second. The 4 possible actions are:

  • 'L': Spin left. If the bar is in state '|', it goes to 'N'. State 'N' goes to '-', '-' goes to '/', and '/' goes to '|'.
  • 'R': Spin right. This is the exact opposite of 'L': 'N' goes to '|', '|' goes to '/', '/' goes to '-', and '-' goes to 'N'.
  • 'S': Stay. The bar remains in its current state.
  • 'F': Flip. The bar is rotated 90 degrees: '|' becomes '-', '-' becomes '|', '/' becomes 'N', and 'N' becomes '/'.

So, the sequence "F03L02" and the starting state of '-' leads to the following sequence: "-|-|N-".

Given a String[] actions representing a sequence of actions, return the shortest program that leads to that sequence. The first character of the sequence is the starting state, so your program should run for K-1 seconds where K is the length of the given sequence. If there are multiple shortest programs that produce the given sequence, return the lexicographically first among them. If the return string has more than 100 characters, return only the first 97 followed by "..." (see last example for clarification).

 

Definition

    
Class:IndicatorMotionReverse
Method:getMinProgram
Parameters:String[]
Returns:String
Method signature:String getMinProgram(String[] actions)
(be sure your method is public)
    
 

Notes

-You can't make an action last more than 99 seconds with a single instruction, but you can use the same instruction multiple times consecutively (see example 2 for further clarification).
-If two programs have the same size, the one that comes earlier lexicographically is the one with the lower ASCII value in the first position at which they differ.
 

Constraints

-actions will have between 1 and 50 elements, inclusive.
-Each element in actions will have between 1 and 50 characters, inclusive.
-Each character of each element of actions will be one of '|', 'N', '-' or '/'.
 

Examples

0)
    
{"-|-|/-/|//////-/"}
Returns: "F03R02L02R01S05R01L01"
The actions needed after the first '-', which is the starting state, are:
-|-|/-/|//////-/
.FFFRRLLRSSSSSRL
which can be optimally represented using the syntax above.
1)
    
{"N"}
Returns: ""
Sometimes you need an empty program.
2)
    
{"||||||||||||||||||||||||||||||||||||||||||||||||||",
 "||||||||||||||||||||||||||||||||||||||||||||||||||",
 "||||||||||||||||||||||||||||||||||||||||||||||||||"}
Returns: "S50S99"
Here you need 149 stays and it is necessary to break them into 2 'S' instructions. The lexicographically first way to do this is S50S99.
3)
    
{"N",
 "-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N",
 "-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N",
 "-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N",
 "-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N",
 "-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N",
 "-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N",
 "-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N",
 "-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N-N"}
Returns: 
"L01R01L01R01L01R01L01R01L01R01L01R01L01R01L01R01L01R01L01R01L01R01L01R01L01R01L01R01L01R01L01R01L..."
In this case the output program has 400 instructions, which is 3x400=1200 characters. Remember to return only the first 97 followed by "...".

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TrafficMonitor

Graph Theory



Used in:

TCO06 Wildcard

Used as:

Division I Level One

Writer:

AdminBrett

Testers:

PabloGilberto , lbackstrom , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6165

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9983&pm=6165

Problem Statement

    You are given a network where each pair of nodes is connected by at most 1 path. Your boss has told you to place traffic monitors on certain nodes to better supervise the network. A single monitor can watch all links directly connected to the node it is attached to. Assuming every link must be watched, return the fewest number of monitors that must be installed.



Nodes i and j share a symmetric link in your network if character j of element i of links is 'Y' ('N' otherwise). A path is a sequence of distinct nodes such that neighbors in the sequence share a link.
 

Definition

    
Class:TrafficMonitor
Method:getMin
Parameters:String[]
Returns:int
Method signature:int getMin(String[] links)
(be sure your method is public)
    
 

Constraints

-links will contain between 1 and 50 elements, inclusive.
-Each element of links will contain exactly N characters, where N is the number of elements in links.
-Each character of links will be 'Y' or 'N'.
-Character i of element i of links will be 'N'.
-Character i of element j of links will equal character j of element i.
-There will be at most one path between any two nodes.
 

Examples

0)
    
{
"NN",
"NN"
}
Returns: 0
There are no edges to monitor.
1)
    
{
"NYNN",
"YNYN",
"NYNY",
"NNYN"
}
Returns: 2
2)
    
{
"NNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNYNNNNNNN",
"NNNNNNNNNNNNNYNNYNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNN",
"NNNNNNNNNNNNNNYNNNNNYNNNNNNNYNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNN",
"YNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNN",
"NYNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNYNNNNN",
"NNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNYNN",
"NNNNNNNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNYNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNYNNYNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNYNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNYN",
"NNNYNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNYNNNYNNN",
"NNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNN",
"NNNNNNNNYYNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNYNNNNNNNNNNNNNNNNNNNNNNYNNNNYNNNNNYNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNYN",
"NNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNY",
"NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNYNN",
"NNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNYNNNNYNNNN",
"NNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNYNNN",
"NNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNYYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNYNNNNNN",
"NNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNYNNNNNNNNYYNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNYNNNY",
"NNNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNYNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNN",
"NNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNYNNNNNNNNNN",
"NNNNNNNNNNNNNNNNYNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNYNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNYNNNNNYNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNNNNNNNNYNNNNNNNNNNNNNNNYNNNNNNNNNN"
}
Returns: 22

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

OrderDoesMatter

Graph Theory, Greedy, Simple Search, Iteration



Used in:

SRM 298

Used as:

Division I Level Two

Writer:

soul-net

Testers:

PabloGilberto , brett1479 , radeye , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6157

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9819&pm=6157

Problem Statement

    Matrices are a common object in mathematics. A NxM matrix is basically a table with N rows of M values each. Given two matrices, one of size AxB and another of size CxD, the following multiplication rules apply:
  • You can only multiply them if B is equal to C.
  • The resultant matrix is of size AxD.
The number of elements in an AxB matrix is A multiplied by B. For example, a 3x7 matrix has 21 elements.

Given a list of matrices, determine if there's an ordering that allows you to multiply all of them. If multiple such orderings exist, choose the one where the result has the most elements. Return the number of elements in the result, or -1 if there is no valid ordering (see examples 0-3 for further clarification). The list of matrices is given as two int[]s, N and M, where the ith elements of N and M represent the number of rows and columns respectively of the ith matrix.
 

Definition

    
Class:OrderDoesMatter
Method:getOrder
Parameters:int[], int[]
Returns:int
Method signature:int getOrder(int[] N, int[] M)
(be sure your method is public)
    
 

Notes

-The association order is not important because we are only interested in the dimensions of the matrices.
 

Constraints

-M will have between 1 and 50 elements, inclusive.
-N and M will have the same number of elements.
-Each element of N and M will be between 1 and 1000, inclusive.
 

Examples

0)
    
{7,3,3}
{3,7,3}
Returns: 49
Here we can legally multiply all the matrices in three different ways:

(3x3)*(3x7)*(7x3) = (3x3) (elements = 9)

(3x7)*(7x3)*(3x3) = (3x3) (elements = 9)

(7x3)*(3x3)*(3x7) = (7x7) (elements = 49)

The maximum number of elements is then 49.
1)
    
{3,5,5}
{5,1,5}
Returns: 3
There's only one legal way to multiply the matrices (3x5)*(5x5)*(5x1)=(3x1) so the answer is 3*1=3.
2)
    
{3,5,5}
{5,2,4}
Returns: -1
There is no legal way to multiply the matrices.
3)
    
{5,2,3}
{2,5,3}
Returns: -1
Again, no legal way to multiply them all.
4)
    
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
Returns: 1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PhoneNetwork

Graph Theory



Used in:

TCO06 Finals

Used as:

Division I Level Three

Writer:

Jan_Kuipers

Testers:

PabloGilberto , lbackstrom , brett1479 , radeye , Olexiy , Andrew_Lazarev

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6150

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9984&pm=6150

Problem Statement

    

We want to build a new phone network between numPoints points. A number of possible cables is available to construct the network. Each of the cables connects two of the points and has an associated quality and cost. We want to select a number of these cables such that:

1) All the points are connected to each other, either directly or via other points.

and

2) The quality/cost ratio (i.e., the sum of the qualities divided by the sum of the costs) is as high as possible.

What is the best achievable ratio? If it is impossible to connect all the points, return -1.

The available cables are described by a String[] cables. Each element of cables consists of four integers separated by single spaces. The first two integers describe the two points connected by the cable. The third integer describes the quality of the cable and the fourth integer describes its cost.

 

Definition

    
Class:PhoneNetwork
Method:bestQuality
Parameters:int, String[]
Returns:double
Method signature:double bestQuality(int numPoints, String[] cables)
(be sure your method is public)
    
 

Notes

-Your return must have relative or absolute error less than 1e-9.
 

Constraints

-numPoints is between 2 and 50, inclusive.
-cables has between 0 and 50 elements, inclusive.
-Each element of cables has length between 0 and 50, inclusive.
-Each element of cables consists of four integers with no leading zeroes, separated by single spaces.
-The first two integers of each element of cables are between 1 and numPoints, inclusive.
-The first two integers of each element of cables are not equal.
-The third and fourth integers of each element of cables are between 1 and 100,000, inclusive.
 

Examples

0)
    
4
{"1 2 6 5","2 3 3 4","3 4 5 2","4 1 3 3"}
Returns: 1.4
By taking cables 1, 2 and 4, we obtain a quality/cost ratio of (6+5+3)/(5+2+3) = 1.4.
1)
    
5
{"1 2 6 5","2 3 3 4","3 4 5 2","4 1 3 3"}
Returns: -1.0
It's impossible to connect point 5 to the others.
2)
    
4
{"1 2 1 10","2 3 3 3","2 4 3 2","3 4 3 1","3 4 2 1"}
Returns: 0.7058823529411765
The cable needed to connect point 1 to the rest is so bad that it pays off to use all the other cables, including the two different cables connecting points 3 and 4.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Manhattan

Simple Math



Used in:

SRM 319

Used as:

Division I Level Three

Writer:

Jan_Kuipers

Testers:

PabloGilberto , lbackstrom , brett1479 , radeye , Olexiy , Andrew_Lazarev , ged

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6149

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9999&pm=6149

Problem Statement

    My whole family lives in Manhattan, and consists of n people numbered 0 through (n - 1). The roads in Manhattan are a bit peculiar: they all go from North to South or from West to East, and together they form a complete grid of roads. Therefore, the distance between two intersections (x,y) and (x',y') equals abs(x-x')+abs(y-y'). Knowing the intersections where my family members live, I'd like to find the two different persons with the furthest distance between them. You are to help me by returning a int[] containing the 0-based indices of the people who form the furthest pair. If there are several furthest pairs, return the one among them with the smallest first index. If there are still multiple pairs left, return the one among them with the smallest second index.



The intersection where the ith family member lives is defined by the following sequence:
xi = (a * yi-1 + b) % m, for i > 0.
yi = (a * xi + b) % m, for i >= 0.
with x0=0.
 

Definition

    
Class:Manhattan
Method:furthestPair
Parameters:int, int, int, int
Returns:int[]
Method signature:int[] furthestPair(int n, int a, int b, int m)
(be sure your method is public)
    
 

Constraints

-n will be between 2 and 250,000, inclusive.
-a, b and m will each be between 1 and 1,000,000,000, inclusive.
 

Examples

0)
    
10
7
13
23
Returns: {2, 6 }
The intersections where my family members live are (0,13), (12,5), (2,4), (18,1), (20,15), (3,11), (21,22), (6,9), (7,16) and (10,14). The 2nd and 6th intersections (zero-indexed) are furthest apart. The distance is abs(2-21)+abs(4-22)=37.
1)
    
10
17
17
17
Returns: {0, 1 }
All of them live at (0,0), so all pairs have distance 0. The lexicographically first pair is {0, 1}. Please note that we are looking for two different persons, so pair {0, 0} is invalid.
2)
    
100
912
1023
103871
Returns: {0, 54 }
Intersections 0 (0,1023) and 54 (96346,97580) are furthest apart.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Palindromist

Dynamic Programming, String Manipulation



Used in:

SRM 294

Used as:

Division I Level Two , Division II Level Three

Writer:

legakis

Testers:

PabloGilberto , brett1479 , radeye , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6115

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9815&pm=6115

Problem Statement

    

A palindrome is a phrase that reads the same forward and backward (ignoring spaces). Given the first half of a palindrome (as described below), you must return a complete palindrome that contains only words from a given set of legal words. The returned palindrome must be a phrase where words are separated by single spaces.

You will be given the first half of the palindrome as a String text containing only letters and no spaces. There are two complete palindromes that can be created from this first half. For example, given "ABC", you could produce either "ABCCBA" or "ABCBA" as the complete palindrome. You must then insert spaces into the complete palindrome such that all the words in the phrase exist in the String[] words

For example, given the list of words { "A", "CANAL", "MAN", "PANAMA", "PLAN" }, and the text "AMANAPLANAC", your method would return the String "A MAN A PLAN A CANAL PANAMA".

If no palindrome can be made, your method should return "". If more than one palindrome can be made, return the one that comes first lexicographically (please note that ' ' comes before all letters).

 

Definition

    
Class:Palindromist
Method:palindrome
Parameters:String, String[]
Returns:String
Method signature:String palindrome(String text, String[] words)
(be sure your method is public)
    
 

Constraints

-text will contain between 1 and 50 characters, inclusive.
-text will contain only uppercase letters ('A'-'Z').
-words will contain between 1 and 50 elements, inclusive.
-Each element of words will contain between 1 and 50 characters, inclusive.
-Each element of words will contain only uppercase letters ('A'-'Z').
 

Examples

0)
    
"AMANAPLANAC"
{ "A", "CANAL", "MAN", "PANAMA", "PLAN" }
Returns: "A MAN A PLAN A CANAL PANAMA"
1)
    
"AAAAA"
{ "AA", "A", "AAA" }
Returns: "A A A A A A A A A"
2)
    
"CBA"
{ "CBABC", "CBAABC" }
Returns: "CBAABC"
3)
    
"RACEFAST"
{ "AR", "CAR", "FAST", "RACE", "SAFE", "CEFA", "ACE", "STTS", "AFEC" }
Returns: "RACE FAST SAFE CAR"
4)
    
"AABAABA"
{ "AA", "AAB", "BAA", "BAB" }
Returns: "AA BAA BAA BAA BAA"
5)
    
"STRAWNOTOOSTUPIDAF"
{ "WARTS", "I", "TOO", "A", "FAD", "STUPID", "STRAW", "PUT", "NO", "ON", "SOOT" }
Returns: "STRAW NO TOO STUPID A FAD I PUT SOOT ON WARTS"
6)
    
"AAAAA"
{ "AAAA" }
Returns: ""
7)
    
"A"
{ "A", "AA" }
Returns: "A"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TreeReconstruct

Graph Theory



Used in:

TCO06 Round 4

Used as:

Division I Level Three

Writer:

lars2520

Testers:

PabloGilberto , brett1479 , radeye , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6110

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9925&pm=6110

Problem Statement

    A tree is a connected graph with no cycles. Starting from a connected tree with positive integral edge lengths, we take a subset of the nodes of that tree. Next, we compute the lengths of the shortest paths between all pairs of nodes in the subset (in the original tree). This gives us a symmetric N*N distance matrix where N is the number of nodes in the subset.



Your task is to reverse this process. Given a N*N distance matrix, you are to reconstruct a tree, if possible. Since there may be many reconstructions, you should return the minimum number of nodes in any reconstruction that agrees with the distance matrix (this will be at least N). If no reconstruction is possible, return -1.



The distance between nodes i and j (indexed from 0) can be found by treating g1[i][j] and g2[i][j] as hexadecimal digits. Putting the two digits together gives the distance (g1 has the more significant digits).
 

Definition

    
Class:TreeReconstruct
Method:reconstruct
Parameters:String[], String[]
Returns:int
Method signature:int reconstruct(String[] g1, String[] g2)
(be sure your method is public)
    
 

Constraints

-g1 and g2 will each contain exactly N elements, where N is between 2 and 50, inclusive.
-Each element of g1 and g2 will contain exactly N hex digits ('0'-'9' and 'A'-'F').
-The distance between each pair of distinct nodes will be positive.
-The diagonal entries of g1 and g2 will be '0'.
-g1 and g2 will each be symmetric.
 

Examples

0)
    
{"0000",
 "0000",
 "0000",
 "0000"}
{"0444",
 "4044",
 "4404",
 "4440"}
Returns: 5
The original tree could have been a star: one central node, with 4 nodes connected to it, each by an edge of length 2. The subset of selected nodes are the 4 non-central nodes.
1)
    
{"0000",
 "0000",
 "0000",
 "0000"}
{"0233",
 "2033",
 "3302",
 "3320"}
Returns: 6
2)
    
{"00001",
 "00001",
 "00011",
 "00100",
 "11100"}
{"066C6",
 "60CA4",
 "6C02C",
 "CA20A",
 "64CA0"}
Returns: 6
3)
    
{"00000",
 "00000",
 "00001",
 "00000",
 "00100"}
{"06839",
 "60E7B",
 "8E0B1",
 "37B0A",
 "9B1A0"}
Returns: 7
4)
    
{"023825",
 "202704",
 "320633",
 "876084",
 "203805",
 "543450"}
{"0198AA",
 "10ED9F",
 "9E0D7F",
 "8DD06E",
 "A97608",
 "AFFE80"}
Returns: 9
5)
    
{"0000",
 "0000",
 "0000",
 "0000"}
{"0121",
 "1012",
 "2101",
 "1210"}
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SeparateConnections

Graph Theory



Used in:

TCO06 Round 1

Used as:

Division I Level One

Writer:

AdminBrett

Testers:

PabloGilberto , lbackstrom , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6095

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9917&pm=6095

Problem Statement

    You are analyzing a communications network with at most 18 nodes. Character j in element i (both 0-based) of mat denotes whether nodes i and j can communicate ('Y' for yes, 'N' for no). Assuming a node cannot communicate with two nodes at once, return the maximum number of nodes that can communicate simultaneously.
 

Definition

    
Class:SeparateConnections
Method:howMany
Parameters:String[]
Returns:int
Method signature:int howMany(String[] mat)
(be sure your method is public)
    
 

Notes

-If node S is communicating with node T then node T is communicating with node S.
 

Constraints

-mat will contain between 1 and 18 elements inclusive.
-Each element of mat will contain exactly N characters, where N is the number of elements in mat.
-Each character in mat will be 'Y' or 'N'.
-Character i of element i of mat will be 'N'.
-Character i of element j will be the same as character j of element i.
 

Examples

0)
    
{
"NYYYY",
"YNNNN",
"YNNNN",
"YNNNN",
"YNNNN"
}
Returns: 2
All communications must occur with node 0. Since node 0 can only communicate with 1 node at a time, the returned value is 2.
1)
    
{
"NYYYY",
"YNNNN",
"YNNNY",
"YNNNY",
"YNYYN"
}
Returns: 4
In this setup, we can let node 0 communicate with node 1, and node 3 communicate with node 4.
2)
    
{
"NNYYYYYYYYYYYYYYYY",
"NNYYYYYYYYYYYYYYYY",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN",
"YYNNNNNNNNNNNNNNNN"
}
Returns: 4
3)
    
{
"NNNNNNNNNYNNNNNYN",
"NNNNNNNNNNNNNNNNN",
"NNNNNNNYNNNNNNNNN",
"NNNNNYNNNNNYNNYYY",
"NNNNNNNNNNNNNNNYN",
"NNNYNNNNNNNNNNYNN",
"NNNNNNNNNYNNNNNNN",
"NNYNNNNNNNNNNNNNN",
"NNNNNNNNNYNNNNNNN",
"YNNNNNYNYNNNNNNNY",
"NNNNNNNNNNNNNNNNN",
"NNNYNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNN",
"NNNNNNNNNNNNNNNNN",
"NNNYNYNNNNNNNNNNN",
"YNNYYNNNNNNNNNNNN",
"NNNYNNNNNYNNNNNNN"
}
Returns: 10

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CrazySwitches

Brute Force, Graph Theory



Used in:

SRM 291

Used as:

Division I Level Two , Division II Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6071

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9812&pm=6071

Problem Statement

    

You are in a house where the light in each room is controlled by a switch that might be located in a different room. Initially, the light in the first room is on, and the lights in all the other rooms are off.

You are currently in the first room and your goal is to end up in the last room, with all the lights in the house off except the light in the last room. You can move directly from any room to any other room, and you can turn any of the switches that are located in your current room. However, you may never enter a dark room or turn off the light in your current room.

You are given a int[] switches describing the locations of the light switches. The light switch for room i is located in room switches[i]. Rooms have 0-based indices. Return the minimal number of moves required to complete your task, or -1 if it is impossible. Only moving from one room to another counts as a move (turning a switch is not counted).

 

Definition

    
Class:CrazySwitches
Method:minimumActions
Parameters:int[]
Returns:int
Method signature:int minimumActions(int[] switches)
(be sure your method is public)
    
 

Constraints

-switches will contain between 2 and 16 elements, inclusive.
-Each element in switches will be between 0 and the number of elements in switches - 1, inclusive.
 

Examples

0)
    
{1, 0}
Returns: 1
You can switch on the light in the last room, move into the last room and switch off the light in the first room.
1)
    
{0, 1}
Returns: -1
You can't do anything.
2)
    
{1, 2, 0}
Returns: 3
You can switch on the light in the last room, move into the last room, switch on the light in the second room, move into the second room, switch off the light in the first room, move into the last room and switch off the light in the second room.
3)
    
{4, 4, 3, 0, 5, 2}
Returns: 7
4)
    
{7, 11, 1, 12, 6, 3, 0, 2, 6, 0, 0, 5, 9}
Returns: 15

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Knights

Graph Theory



Used in:

SRM 303

Used as:

Division I Level Two

Writer:

Snail

Testers:

PabloGilberto , brett1479 , Yarin , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6070

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9824&pm=6070

Problem Statement

    

There are several knights located on a NxN chessboard. Chessboard rows are numbered from 1 to N, inclusive. Chessboard columns are numbered with single characters from 'A' to 'A'+N-1, inclusive. For example, a standard 8x8 chessboard has rows 1...8 and columns A...H.

A knight is a chess piece that attacks the following squares (marked with X symbols):



If one of those squares is occupied by some other knight, those two knights are attacking each other.

An arrangement of knights is called friendly if no knight attacks another knight. Your task is to determine the minimum number of knights that can be removed to make a friendly arrangement. You will be given an int N denoting the size of the chessboard and a String[] pos containing the knight positions. Each element of pos will contain a space separated list of <COL><ROW> knight positions on the board where <COL> is the column and <ROW> is the row. Each <COL> is a letter between 'A' and 'A'+N-1, inclusive, and each <ROW> is an integer between 1 and N, inclusive, with no leading zeros. There will be no leading or trailing spaces.

 

Definition

    
Class:Knights
Method:makeFriendly
Parameters:int, String[]
Returns:int
Method signature:int makeFriendly(int N, String[] pos)
(be sure your method is public)
    
 

Constraints

- N will be between 1 and 26, inclusive.
- pos will contain between 1 and 50 elements, inclusive.
- pos will be formatted as described in the statement.
- Each element of pos will contain between 2 and 50 characters, inclusive.
- No two knights will occupy the same position.
 

Examples

0)
    
5
{"A2 A4", "B1 B5", "D1 D5 E2 E4 C3"}
Returns: 1
8 knights on the chessboard are attacked by knight C3, so it should be removed.
1)
    
2
{"A1 A2 B1 B2"}
Returns: 0
This is a 2x2 chessboard, so no knight is under attack.
2)
    
6
{"A1 A5 B3 C1 C5 D2 D4 E6 F5"}
Returns: 3
One possible way is to remove B3, C5 and D4.
3)
    
8
{"A2 A4 A5 A6 B2 B5 B6 B7 B8",
 "C3 C8 D1 D2 D3 D4 D5 D6 D8",
 "E1 E3 E8 F1 F2 F8 G3 G5 H4 H7 H8"}
Returns: 12
4)
    
9
{"A3 A4 A5 A7 A8 B6 B8 C3 C6",
 "C7 C9 D4 D5 D8 D9 E1 E3 E7",
 "F2 G2 G6 G7 H2 H9 I2 I4 I5",
 "I6 I7 I8 I9"}
Returns: 10

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CountryWar

Dynamic Programming, Graph Theory, Search



Used in:

SRM 288

Used as:

Division I Level Three

Writer:

timmac

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6068

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9809&pm=6068

Problem Statement

    

Your country has several army units. There are several other countries, each of which is considered to be either an enemy or neutral, and each of which has several army units of its own.

A war consists of a series of battles. Once you initiate war with a neighboring country, war will proceed until either country has no remaining army units. After defeating another country in war, you own their territory. That is, their territory is added to yours forming one new larger territory. You can only initiate war with a country that borders some part of the territory you already own.

In any single round of battle, exactly one of the two countries involved will lose an army unit. If country A attacks country B, where A and B have a and b army units, respectively, then the probability that B will lose an army unit during the battle is a2/(a2+a*b+b2), otherwise A will lose an army unit. Note that a and b correspond to the total number of units in countries A and B, respectively.

Your goal is to defeat all of the enemy nations. While it is not required that you defeat any of the neutral nations, doing so may be necessary in order to reach other enemy countries (see examples 2 and 3).

You are given a String[] armies, describing each country. Each element of armies is formatted as "type units borders" (quotes added for clarity). type is one of 'Y', 'E' or 'N', indicating if the country is yours, an enemy, or neutral. units is an integer indicating how many army units are held by that country. borders is a space delimited list of zero or more integers, indicating the zero-based indices of adjacent countries.

You are to return a double indicating the probability that you can defeat all of your enemy nations without all of your army units being lost, assuming that you choose your order of attack optimally.

 

Definition

    
Class:CountryWar
Method:defeatAll
Parameters:String[]
Returns:double
Method signature:double defeatAll(String[] armies)
(be sure your method is public)
    
 

Notes

-The graph described by the bordering countries does not necessarily represent a planar graph.
-The graph described by the countries is not necessarily a connected graph (see example 5).
-Return value must be within 1e-9 absolute or relative error of the actual result.
 

Constraints

-armies will contain between 1 and 15 elements, inclusive.
-Each element of armies will be formatted as "type units borders" (quotes added for clarity).
-Each type will be 'Y', 'E' or 'N'.
-Exactly one element of armies will be of type 'Y'.
-Each units will be an integer between 1 and 20, inclusive, with no leading zeros.
-Each number represented in borders will be an integer with no leading zeros, between 0 and n-1, inclusive, where n is the number of elements in armies.
-Within a single element of armies, the numbers represented in borders will contain no duplicates.
-The borders described will be symmetric (that is, if a borders b, then b borders a).
 

Examples

0)
    
{"Y 1 1",
 "E 1 0"}
Returns: 0.3333333333333333
Here, you and your enemy each have exactly one army. Using the formula, 12 / (12 + 1*1 + 12) = 1/3.
1)
    
{"Y 2 1",
 "E 1 0"}
Returns: 0.7142857142857142
Here, superior strength is an advantage. In the first round of battle, there is a 4/7 chance of our enemy losing his only army. In the 3/7 chance that we get to a second round of battle, there is a 1/3 chance of winning. Thus, our total chances of winning are 4/7 + 3/7 * 1/3 = 5/7.
2)
    
{"Y 1 1",
 "E 1 0 2",
 "N 1 1"}
Returns: 0.3333333333333333
Our first battle is against our enemy, which we have a 1/3 chance of winning. Since we are not required to defeat neutral countries, we do not need to continue after that.
3)
    
{"Y 1 1",
 "N 1 0 2",
 "E 1 1"}
Returns: 0.1111111111111111
Here, we again have three countries lined up in a row, but this time, we are forced to first attack the neutral country, so that we can get to the enemy. We have a 1/3 chance of winning each war, thus a 1/9 chance of successfully completing both.
4)
    
{"Y 2 1 2",
 "E 2 0 2",
 "E 1 0 1"}
Returns: 0.16250944822373392
There are two enemy nations to attack, so our task is to determine which order of attack is optimal.
5)
    
{"Y 1",
 "E 1"}
Returns: 0.0
There is no path connecting you with your enemy, therefore you cannot possibly attack (or defeat) them.
6)
    
{"Y 1"}
Returns: 1.0
There is only you, and nobody to defeat, so you're guaranteed to be successful.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PendingTasks

Dynamic Programming, Graph Theory



Used in:

TCHS SRM 8

Used as:

Division I Level Three

Writer:

sql_lall

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6066

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10060&pm=6066

Problem Statement

    When scheduling tasks to be executed by a person, it is sometimes the case that when one task is completed, a later task suddenly becomes more important. In these situations, it is said that the later task is a 'Supertask' of the completed one.



In addition, when a task reaches a certain level of importance, it must be executed immediately. Each task is initially given a priority of 0. Whenever a task is completed, the priority of its Supertask increases by 1. If at some moment one of the tasks has a priority of 2, and has not been previously executed, it must be executed immediately. If no remaining task has a priority of 2, a single unexecuted task of your choice must be executed (you can not wait and must execute one of them).



You have been given N tasks (referenced by numbers 0 to N-1) that must be executed. All of these tasks (with the exception of the last) have a single Supertask, and you are guaranteed that the reference number of a task will always be lower than the reference number of its Supertask. The last task has no supertask, instead the number -1 is used. You also wish to execute the last task (with reference number N-1) as late as possible. Every task takes one minute to complete execution. Given the supertasks for each task, return the latest time (in minutes) that the last task can be started, if you start executing tasks at time 0.



You will be given the supertasks as a int[] supertasks, where element i of supertasks contains the reference number of the supertask for task i.
 

Definition

    
Class:PendingTasks
Method:latestProcess
Parameters:int[]
Returns:int
Method signature:int latestProcess(int[] supertasks)
(be sure your method is public)
    
 

Notes

-If a task is executed after its Supertask, then its execution has no bearing on the priority of the Supertask.
-Tasks can only be executed once
 

Constraints

-supertasks will contain between 1 and 50 elements, inclusive
-Element i of supertasks will be between i + 1 and (number of elements in supertasks - 1), inclusive, except the last element of supertasks, which will be -1.
 

Examples

0)
    
{4,4,4,4,-1}
Returns: 2
The final task is a supertask of all other tasks. Whenever you finish any two of first four tasks, the priority of the last will have risen from 0 to 2, so it must execute immediately. This happens after two tasks, so the latest it can start is after two minutes.
1)
    
{1,2,3,4,-1}
Returns: 4
You can do the tasks in order, putting the final task last, starting it at the fourth minute.
2)
    
{-1}
Returns: 0
The final task is also the only task, so it must be executed immediately.
3)
    
{6,6,6,7,7,7,8,8,-1}
Returns: 7
We have the following tree:
      8
   /     \
  6       7
/ | \   / | \
0 1 2   3 4 5
We can not complete all of tasks 0 to 7 before task 8 because:

a) one of tasks 0, 1, 2 must be completed after task 6.

b) one of tasks 3, 4, 5 must be completed after task 7.

c) task 8 must be started as soon as both 6 and 7 are finished - so one of 0 to 5 will not be completed at that moment.

One of the possible orderings which starts the final task at the 7th minute is the following: 0, 1, 6, 2, 3, 4, 7, 8.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RoutePackets



Used in:


Used as:



Writer:


Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6058

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9881&pm=6058

Problem Statement

    We can think of a computer network as a undirected graph where nodes represent routers and edges represent connections between the routers. In this network, there are a number of packets, each of which has a source and a target. Over a number of discrete time steps, each packet must travel from its source to its target. During one time step, a packet at router u may move to router v, if there is a link between u and v. However, only one packet may use a link between u and v during a particular time step (if one packet uses a link to go from u to v, no other packet can use that link to go from v to u during the same time step). The problem is to figure out the best way to route the packets through the network so that they get to their destinations as soon as possible.



You will be given an int, 2<=N<=100, representing the number of nodes in the graph. A String[], g will specify the edges (up to 4950 of them), where each element is of the form "u v", where u and v are distinct integers between 0 and N-1, inclusive, indicating an edge between node u and node v. There will be at most one edge between a pair of nodes. A String[], packets, will specify the packets to be sent in the network, where 10<=|packets|<=2,000. Each element will be formatted as "s t", indicating a packet with source s and target t, where s does not equal t. These graphs will be randomly generated as described at the end of the problem statement. Furthermore, the graphs will be connected.



Your task is to come up with a routing plan for the packets through the network. You should return a String[], each element of which represents the locations of the packets after each time step. Each element of the String[] should be a space delimited list of the packets' locations at a time step corresponding to the index of the element (the first element of the return corresponds to the locations of the packets after the first time step). The list should give the locations in the same order that the packets are given to you.



For example, consider the simple network with 2 nodes and 2 packets:

N=2

g={"0 1"}

packets={"0 1","1 0"}

In this case, there are two packets trying to go in opposite directions along the one link. One possible return would be:

{"0 0","1 0"}

This indicates that in the first time step, the second packet moves along the link from node 1 to node 0. Since that link is in use, the first packet cannot also use it, so during the second time step, the first packet moves from node 0 to node 1, and at this point all packets have reached their destinations. Another valid return would be {"0 1","1 1","1 0"}. In this return, none of the packets moved during the first time step. While valid, this is clearly suboptimal.



Your program will be scored based on the quality of your method's return, and the time it takes your method to execute. If your method's return is invalid in any way or if not all the packets reach their destinations, you will get a 0. Otherwise, your score for a test case will be given by:

quality2 - 10 * execution time      (quality is defined below, time is in seconds)
If the quality or the above formula turns out to be negative, the score is set to 0. Your overall score will be the sum over all test cases of SCORE/OPT, where OPT is the highest score anyone has achieved on a test case (0/0 = 1 here). Thus, if you score 10 on one test case, and someone else scores 20 on the same test case, you will get 10/20 = 0.5 towards your final score for that test case.



The quality term used above will be the percent improvement of your solution over a naive solution that routes packets over a random shortest path. In the naive solution, if a packet is being routed to node v, and is currently at node u, then a node is chosen at random out of all nodes that are on some shortest path from u to v and are also connected to u. The packet will eventually be sent from u to that node, with conflicts along the link resolved by letting a random packet use the link.



Finally, there are dozens of realistic and interesting classes of graphs that could be randomly generated and used here. One class that has drawn a great deal of interest in recent years is ad-hoc networks. To simulate these graphs, we will first select a random value for N, the number of nodes. Each node will then be assigned a random x and y value in a cartesian plane, at a distance of no more than 50 from the origin. Then, we will select random values for the lower and upper bounds on each node's range (5<=lower<upper<30). Each node will be assigned a range uniformly between these bounds. Two nodes will be able to communicate if their distance from each other is less than both their ranges. If the network generated is not connected, it will be scrapped and a new attempt will be made. Otherwise, a random number of packets will be generated, the sources and sinks of which are random. Here is pseudocode to generate a graph. The notation [x,y] indicates a random value between x and y, inclusive (the value is floating point unless an integer is clearly required). Roughly 30% of generated graphs are connected.
	N = [2,100]
	lower = [5,30]
	upper = [5,30]
	if(upper < lower)swap(lower,upper)
        for(i = 0 to N-1){
		do{
			x[i] = [-50,50]
			y[i] = [-50,50]
		}while(x[i]*x[i]+y[i]*y[i] > 50*50);
		r[i] = [lower,upper]
	}
	for(i = 0 to N - 1){
		for(j = 0 to i-1){
			if(dist(i,j) < range[i] && dist(i,j) < range[j]){
				connected(i,j) = connected(j,i) = true
			}
		}
	}
	M = [10,2000]
	for(i = 0 to M-1){
		do{
			packets(i,0) = [0,N-1]
			packets(i,1) = [0,N-1]
		}while(packets(i,0) == packets(i,1));
		
	}
 

Definition

    
Class:RoutePackets
Method:route
Parameters:int, String[], String[]
Returns:String[]
Method signature:String[] route(int N, String[] graph, String[] packets)
(be sure your method is public)
    
 

Notes

-The time limit is 20 seconds.
-The memory limit is 1 gigabyte.
-The thread limit is 32.
-There may be multiple packets corresponding to a single pair of nodes.
-To reduce variance, the naive algorithm explained above is run 5 times, and the median number of steps is used for comparison.
 

Examples

0)
    
"176"
Returns: 
"The graph of 9 nodes in adjacency matrix format:<pre>000100100
001001010
010110000
101010100
001100001
010000010
100100000
010001000
000010000
</pre>The packets to be sent:<pre>8 5
6 7
4 1
0 6
7 4
7 1
3 4
4 7
5 1
7 1
0 7
5 0
0 8
8 0
1 8
7 8
3 7
7 6
0 4
6 1
</pre>"
The naive solution for this test cases takes 13 steps. Hence, if your solution took only 12 steps, it would receive a quality score of (100*(13-12)/13)2 = 59.2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CheapestTabComplete

Dynamic Programming



Used in:

TCCC06 Qual 2

Used as:

Division I Level Two

Writer:

AdminBrett

Testers:

PabloGilberto , Cosmin.ro , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6045

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10094&pm=6045

Problem Statement

    You are in a chat room that supports nickname tab-completion. Suppose the input buffer now contains the string s and you decide to use the completion facility. The first time you press tab you will be shown the lexicographically first element of names that has s as a prefix. Pressing tab again will give the lexicographically second, and so forth. Once the possible options are exhausted the tab key will do nothing. Having found a completion that suits you, you may either press enter to complete the word you are typing, or continue typing characters into the input buffer. If you decide to type characters, they will be appended to the current completion. Your goal is to type the word w, followed by the enter key, using as few keystrokes as possible. Each character and each tab key count as single keystrokes. By interchanging character typing and tab completion sequences as many times as you like, return the fewest number of keystrokes required.
 

Definition

    
Class:CheapestTabComplete
Method:getFewest
Parameters:String[], String
Returns:int
Method signature:int getFewest(String[] names, String w)
(be sure your method is public)
    
 

Notes

-If the buffer is empty, then every element of names is a possible completion for the buffer.
-The only allowed keystrokes are letters, tabs, and enter.
 

Constraints

-names will contain between 0 and 50 elements, inclusive.
-Each element of names will contain between 1 and 50 lowercase letters ('a'-'z'), inclusive.
-w will contain between 1 and 50 lowercase letters ('a'-'z'), inclusive.
 

Examples

0)
    
{}
"myname"
Returns: 7
Since tab is useless, we type in the 6 letters of myname and then press enter.
1)
    
{"myn","myname"}
"myname"
Returns: 3
Here we press tab twice, and then enter.
2)
    
{"abc","ab","abcd","frankies","frank","a","a"}
"frankie"
Returns: 5
Here we type 'f', then tab, then 'i', 'e', and finally enter.
3)
    
{"a","a","f","f","fr","fr","fra","fra","fran","fran","frank","frank"}
"frankie"
Returns: 8
Due to the weird set of names, tab is of no use.
4)
    
{"a","a","bcde","bcde","bcde","bcdefghij"}
"bcdefghijk"
Returns: 6
5)
    
{"aaaa","aaaa","aaaa","aaaa","aaaa"}
"aaaaaaaaaaaaaaaaaaaaaaa"
Returns: 21

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BlindMazeSolve

Dynamic Programming, Search



Used in:

TCO06 Round 2

Used as:

Division I Level Three

Writer:

AdminBrett

Testers:

PabloGilberto , lbackstrom , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6044

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9891&pm=6044

Problem Statement

    Each character in maze will be '.' or 'X' denoting a free square or an obstacle, respectively. Starting on some free square, and moving exclusively through free squares, your goal is to leave the confines of the maze through its left edge. Each move you make is either 'U', 'D', 'L', or 'R' denoting up, down, left, and right respectively. Moving upward decreases which element of maze you are in, while moving leftward decreases which character you are at in a particular element. Nothing happens (your position does not change) if you move into an obstacle, or try to leave the maze other than leftward. Similarly, nothing happens if you issue a move and you have already left the maze (you already won).



Your friend has decided to challenge you by trying to solve the maze with the monitor off. This means you do not know which position you have started in or if you have won. Return the shortest sequence of moves that will solve the maze regardless of your initial position. If there are multiple shortest solutions, return the one that occurs first lexicographically. If there is no solution, return an empty string.
 

Definition

    
Class:BlindMazeSolve
Method:getSolution
Parameters:String[]
Returns:String
Method signature:String getSolution(String[] maze)
(be sure your method is public)
    
 

Constraints

-maze contains between 1 and 5 elements, inclusive.
-Each element of maze will contain between 1 and 4 characters, inclusive.
-Each element of maze will contain the same number of characters.
-Each character in maze will be '.' or 'X'.
-maze will contain at least one '.'.
 

Examples

0)
    
{".X"}
Returns: "L"
Left will win immediately, so we return "L".
1)
    
{
"..",
".."
}
Returns: "LL"
Regardless of your initial position, moving left twice will result in winning.
2)
    
{
"X..",
"X..",
"XXX"
}
Returns: ""
No way to win here.
3)
    
{
"X...",
"XXX.",
"X...",
"X.XX",
"..XX"
}
Returns: "RRDDLLDDLL"
4)
    
{".XX."}
Returns: ""
If you happen to be in the rightmost position, you cannot win.
5)
    
{
"XXX.",
"..X.",
"X...",
"XX..",
"X..."
}
Returns: "DDDRULULULL"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

StrangeParticles

Graph Theory



Used in:

SRM 299

Used as:

Division II Level Three

Writer:

Vovka

Testers:

PabloGilberto , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6040

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9820&pm=6040

Problem Statement

    

There are a number of strange particles flying in space and interacting with each other. When two particles collide, three outcomes are possible:

  • 1.) Nothing happens
  • 2.) The first particle disappears
  • 3.) The second particle disappears

You will be given a String[] interacts, where the jth character of the ith element indicates what happens when the ith and jth particles collide. It will be '+' if the ith particle disappears, '-' if the jth particle disappears, and '0' (zero) if nothing happens.

The particles will randomly collide and interact with each other for some period of time. You don't know the order or the number of interactions that will occur. After all the interactions are over, there will be a number of particles that have not disappeared. Return the lowest possible value for this number.

 

Definition

    
Class:StrangeParticles
Method:remain
Parameters:String[]
Returns:int
Method signature:int remain(String[] interacts)
(be sure your method is public)
    
 

Constraints

-interacts will contain between 1 and 50 elements, inclusive.
-Each element of interacts will contain the same number of characters as there are elements in interacts.
-Each character in interacts will be '+', '-' or '0'.
-Character i in element i of interacts will be '0'.
-Character i in element j of interacts will be opposite to character j in element i ('-' is opposite to '+' and '+' is opposite to '-', '0' is opposite to itself)
 

Examples

0)
    
{"0+-","-0+","+-0"}
Returns: 1
Three particles form a cycle. Only one particle can remain.
1)
    
{"000","000","000"}
Returns: 3
No particle can disappear at all.
2)
    
{"0++++++++++++++",
 "-0+++++++++++++",
 "--0++++++++++++",
 "---0+++++++++++",
 "----0++++++++++",
 "-----0+++++++++",
 "------0++++++++",
 "-------0+++++++",
 "--------0++++++",
 "---------0+++++",
 "----------0++++",
 "-----------0+++",
 "------------0++",
 "-------------0+",
 "--------------0"}
Returns: 1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Wizards

Graph Theory



Used in:

SRM 299

Used as:

Division I Level Three

Writer:

Vovka

Testers:

PabloGilberto , brett1479 , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6039

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9820&pm=6039

Problem Statement

    

The inhabitants of a certain magical country are known to be clever wizards. Their King decided to test how clever they really were.

He took 3 hats (2 white and 1 black) and put 2 smart wizards around a table. He put a white hat on one of the wizards and a black hat on the other. Each wizard could see what hat was on his neighbor, but could not see what hat was on his own head. The wizards knew that there were 2 white hats and 1 black hat. The King asked: "Do you know what hat is on your head?", and the wizard with the white hat answered: "Yes". It's clear how he knew: he had seen the black hat on his neighbor, and knowing that there was only 1 black hat, concluded that his own hat was white.

The King then decided to complicate their task a bit, and he put white hats on both the wizards. He asked: "Do you know what hat is on your head?", and both wizards answered together: "No". He asked again: "Do you know what hat is on your head?", and both wizards then answered: "Yes, we know. We have white hats on our heads!". How did they find out? When the question was first asked, the first wizard had seen the white hat on his neighbor, but didn't know the color of his own hat, so he answered "No". After hearing his neighbor's answer to the same question, he realized that his neighbor was in the same situation. Therefore, both wizards knew that they were wearing white hats when the question was asked a second time.

Let's consider a more general scenario. You are given an int wizards representing the number of wizards participating in the test, and a int[] hats representing all the hats possessed by the King. Each element of hats represents a different color, and the ith element of hats is the number of hats of color i. You are also given a int[] hatsOnWizards, the ith element of which represents the number of hats of color i that are placed on wizards' heads (each wizard will receive exactly one hat). The wizards all know what hats are initially possessed by the King. Each wizard can see the hats worn by all the other wizards, but cannot see the hat on his own head. Each time the King asks his question, the wizards all answer simultaneously, and each wizard can hear the answers given by all the other wizards. Return the number of times the King must ask his question before at least one wizard will know the color of his own hat. The King will always ask the question at least once. If no wizard will ever know the color of his own hat, return -1.

 

Definition

    
Class:Wizards
Method:questions
Parameters:int, int[], int[]
Returns:int
Method signature:int questions(int wizards, int[] hats, int[] hatsOnWizards)
(be sure your method is public)
    
 

Constraints

-wizards will be between 1 and 75, inclusive.
-hats will contain between 2 and 5 elements, inclusive.
-Each element of hats will be between 1 and 15, inclusive.
-hatsOnWizards and hats will contain the same number of elements.
-Each element of hatsOnWizards will be between 0 and the corresponding element in hats, inclusive.
-All elements of hatsOnWizards will sum up to wizards.
 

Examples

0)
    
2
{1,2}
{1,1}
Returns: 1
The first example from the problem statement.
1)
    
2
{1,2}
{0,2}
Returns: 2
The second example from the problem statement.
2)
    
2
{2,2}
{0,2}
Returns: -1
No wizard will ever know the color of his own hat.
3)
    
18
{7,8,9}
{5,4,9}
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FamilyTree

Graph Theory



Used in:

TCO06 Round 3

Used as:

Division I Level Two

Writer:

dgoodman

Testers:

PabloGilberto , lbackstrom , brett1479 , radeye , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6029

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9922&pm=6029

Problem Statement

    We are keeping a family tree. We update the data by adding information as it becomes available. When information arrives that is not consistent with the previous data, we need to recognize that fact immediately. We will enforce only the most obvious rules:
  • A person is either male or female.
  • A child's parent cannot be the child itself or a descendant of the child
  • A child has two parents, one male and the other female.
(A person is a descendant only of his parents, grandparents, greatgrandparents, etc.)

Each piece of data gives either the names of a child and parent or the name of a person and that person's gender. All occurrences of a name represent the same person. Create a class FamilyTree that contains a method firstBad that is given a String[] data. The method returns the (0-based) index of the first element of data that is inconsistent with the previous elements of data, or returns -1 if all the data is consistent.

Each element of data will be formatted in one of these two forms:

      "childname parentname"
      "name gender" 
where the two parts are separated by a single space character, each name is all uppercase letters 'A'-'Z' and gender is a single lowercase letter, either 'm' or 'f'.
 

Definition

    
Class:FamilyTree
Method:firstBad
Parameters:String[]
Returns:int
Method signature:int firstBad(String[] data)
(be sure your method is public)
    
 

Constraints

-data will contain between 1 and 50 elements, inclusive.
-Each element of data will be formatted as above.
-Each element of data will contain between 3 and 50 characters, inclusive.
 

Examples

0)
    
{"BOB JOHN","BOB JOHN","BOB MARY","BOB m","AL f"}
Returns: -1
Repeated data elements just give us more confidence. This data is all consistent. BOB's 2 parents are JOHN and MARY (it is not yet known which is the father and which is the mother), and BOB is male. We also know that AL is female.
1)
    
{"BOB JOHN","BOB MARY","MARY JOHN","JOHN f","MARY f","AL f"}
Returns: 4
The first 4 elements are considered consistent. They describe that BOB's 2 parents are JOHN and MARY and that (unconventionally) MARY is JOHN's child. JOHN is female. But "MARY f" is inconsistent with this since that makes both of BOB's parents female.
2)
    
{"BOB JOHN", "CARLA BOB", "JOHN CARLA"}
Returns: 2
After the first 2 elements we know that CARLA is a descendant of JOHN, so "JOHN CARLA" cannot be added.
3)
    
{"BOB RICK", "AL RICK", "AL PAULA", "PAULA LINUS", "LINUS BOB","BOB PAULA"}
Returns: 5
The first 5 elements are consistent. BOB's descendant AL was a child of RICK and PAULA, and RICK is BOB's parent. His other parent could not be PAULA since PAULA is his descendant so the final element is the first one that is inconsistent.
4)
    
{"JOHN f", "JOHN m"}
Returns: 1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BobTrouble

Graph Theory



Used in:

SRM 292

Used as:

Division I Level Two

Writer:

dgoodman

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=6016

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9813&pm=6016

Problem Statement

    My company has given me a list containing the name of each employee along with the name of his supervisor (who is also an employee) if he has one. The company wants to know whether the list is consistent and, if so, how many of the employees are supervisors (supervise at least one employee). "Consistent" means that there is no supervision cycle in which A supervises himself or A supervises B who supervises C ... who supervises A. It is permissible to have multiple employees who have no supervisor.

But ... we have Bob trouble. All the employees have distinct names, except that there may be multiple distinct employees whose names are "BOB". So there may be multiple ways to put together the supervision hierarchy. We want to construct the hierarchy so as to minimize the number of supervisors.

Create a class BobTrouble that contains a method minSupers that is given a String[] name and a String[] bossName giving the names of all the employees and their bosses. It returns the minimum number of supervisors that can appear in the supervision hierarchy. If no supervision hierarchy is consistent, it returns -1.

Each element of name refers to a distinct employee, and the supervisor of the i-th element is given by the i-th element of bossName ("*" indicates that the employee has no supervisor). Every employee is listed in name.

 

Definition

    
Class:BobTrouble
Method:minSupers
Parameters:String[], String[]
Returns:int
Method signature:int minSupers(String[] name, String[] bossName)
(be sure your method is public)
    
 

Constraints

-name contains between 1 and 50 elements, inclusive.
-Each element of name contains between 1 and 10 uppercase letters ('A'-'Z'), inclusive.
-The elements of name are distinct, except that "BOB" may appear more than once.
-bossName contains the same number of elements as name.
-Each element of bossName is "*" or matches at least one element of name.
 

Examples

0)
    
{"BOB","BOB","BOB"}
{"BOB","*","BOB"}
Returns: 1
There are 3 possible supervisory hierarchies: 1) the middle BOB supervises the first BOB who supervises the last BOB, 2) the middle BOB supervises the last BOB who supervises the first BOB, and 3) the middle BOB supervises the first BOB and also supervises the last BOB. This last choice gives the fewest supervisors.
1)
    
{"JOHN","AL","DON","BOB"}
{"*","*","*","*"}
Returns: 0
All the employees are unsupervised, so there are no supervisors.
2)
    
{"BOB","BOB","BOB"}
{"*","*","BOB"}
Returns: 1
There are 2 possible hierarchies (the third BOB can be supervised by either of the other BOBs). Either way, exactly one of the BOBs is a supervisor.
3)
    
{"BOB", "BOB", "JACK"}
{"BOB", "BOB", "*"}
Returns: -1
The first BOB must be supervised by the second BOB (it is illegal to supervise yourself) and the second BOB must be supervised by the first BOB. But this is a supervision cycle, so there is no legal hierarchy satisfying this data.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

IntegerGenerator

Simple Math, String Manipulation



Used in:

SRM 281

Used as:

Division I Level One , Division II Level Two

Writer:

lovro

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5984

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8078&pm=5984

Problem Statement

    

As part of a larger scale project, you need to write a component which generates consecutive positive integers. Only certain digits may appear in the input and in the integers generated, and leading zeros aren't allowed.

You are given a int[] allowed containing the list of allowed digits, and a String current representing the current integer. Return a String representing the first integer larger than current composed only of digits in allowed.

If current represents an invalid integer according to the first paragraph, return "INVALID INPUT" (quotes for clarity).

 

Definition

    
Class:IntegerGenerator
Method:nextInteger
Parameters:int[], String
Returns:String
Method signature:String nextInteger(int[] allowed, String current)
(be sure your method is public)
    
 

Constraints

-allowed will contain between 0 and 10 elements, inclusive.
-Each element in allowed will be between 0 and 9, inclusive.
-allowed will contain no duplicates.
-current will contain between 1 and 10 digits ('0'-'9'), inclusive.
 

Examples

0)
    
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
"16"
Returns: "17"
With all digits available, the next number is 17.
1)
    
{ 0, 1, 2, 3, 4, 5, 6, 8, 9 }
"16"
Returns: "18"
The digit 7 is no longer allowed, so the next smallest valid integer is 18.
2)
    
{ 3, 5, 8 }
"548"
Returns: "INVALID INPUT"
The current number may not contain disallowed digits.
3)
    
{ 5, 3, 4 }
"033"
Returns: "INVALID INPUT"
Leading zeros aren't allowed either.
4)
    
{ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }
"999"
Returns: "1000"
5)
    
{ 0, 1, 2, 3, 4, 5 }
"0"
Returns: "INVALID INPUT"
The generator only works with positive integers.
6)
    
{ 1 }
"1"
Returns: "11"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GalaxyExpedition

Graph Theory



Used in:

SRM 290

Used as:

Division I Level Three

Writer:

hauser

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5981

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9811&pm=5981

Problem Statement

    

It's the year 2051. You have some free time in June this year and want to visit an interesting galaxy. You will need some machines during your trip and you are wondering how many of them you can take.

There are a number of machines in a store. Each machine may depend on other machines to work properly, and you want all the machines you take to work. You noticed that although machine A may not depend directly on machine B, you may be unable to take A without B because of some indirect dependency. For example, if machine A is dependent on machine C and machine C is dependent on B, you cannot take machine A without machine B.

You discovered an interesting rule while selecting your machines. If a machine A depends on machines B and C, then B is dependent on C, C is dependent on B, or both B and C depend on each other. Although the rule you found is true for direct dependencies, you were able to prove that it also holds for indirect dependencies.

You want to buy K different machines such that all of them will work properly. You are given a String[] dependencies describing the dependencies between the machines. Element i of dependencies is a space delimited list of machines that machine i is directly dependent on. Return a int[] with all possible positive values for K in ascending order.



Example:
{"1 2","0 2","3",""}
  • Machine 0 needs machines 1 and 2 to work
  • Machine 1 needs machines 0 and 2 to work
  • Machine 2 needs machine 3 to work
  • Machine 3 does not need any other machine to work

The allowed K values are 1 (you take only machine 3), 2 (you take machines 2 and 3) and 4 (you take all the machines). So you should return {1,2,4}.

 

Definition

    
Class:GalaxyExpedition
Method:possibleValues
Parameters:String[]
Returns:int[]
Method signature:int[] possibleValues(String[] dependencies)
(be sure your method is public)
    
 

Notes

-First machine has index 0, second has index 1 and so on.
 

Constraints

-dependencies contains between 1 and 50 elements, inclusive.
-Each element of dependencies contains between 0 and 50 characters, inclusive.
-Each element of dependencies is a space delimited list of integers.
-Each integer in dependencies is between 0 and the number of elements in dependencies - 1, inclusive, and contains no extra leading zeros.
-Each element of dependencies contains no duplicate values.
-Element i of dependencies does not contain the value i.
-If a machine A depends on machines B and C, then B is dependent on C, C is dependent on B, or both B and C depend on each other.
 

Examples

0)
    
{"1 2","0 2","3",""}
Returns: {1, 2, 4 }
The example from the problem statement.
1)
    
{"1","2","0"}
Returns: {3 }
We have to take all three machines.
2)
    
{"1","0","3","2"}
Returns: {2, 4 }
We can take a pair {0,1} or {2,3}, and as always we can take all the machines.
3)
    
{"","2 0","0 1","0 4","3 0"}
Returns: {1, 3, 5 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GalaxyTrip

Brute Force, Graph Theory



Used in:

SRM 290

Used as:

Division II Level Three

Writer:

hauser

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5980

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9811&pm=5980

Problem Statement

    

It's the year 2059. You have some free time in May this year and want to visit an interesting galaxy. You will need some machines during your trip and you are wondering how many of them can you take.

There are a number of machines in a store. Each machine may need some other machines to work properly, and you want all the machines you take to work. Luckily for you, in the year 2053, a special rule was introduced to make customers' lives easier. The rule says that if a machine A depends on another machine B, then machine B also depends on machine A.

You want to buy K different machines such that all of them will work properly. You are given a String[] dependencies describing the dependencies between the machines. Element i of dependencies is a space delimited list of machines that machine i is dependent on. Return a int[] with all possible positive values for K in ascending order.





Example:
 {"1 2", "0", "0", ""} 
  • Machine 0 needs machines 1 and 2 to work
  • Machine 1 needs machine 0 to work
  • Machine 2 needs machine 0 to work
  • Machine 3 does not need any other machine to work

The allowed K values are 1 (you take only machine 3), 3 (you take machines 0,1,2) and 4 (you take all the machines). So you should return {1,3,4}.

 

Definition

    
Class:GalaxyTrip
Method:possibleValues
Parameters:String[]
Returns:int[]
Method signature:int[] possibleValues(String[] dependencies)
(be sure your method is public)
    
 

Notes

-First machine has index 0, second has index 1 and so on.
 

Constraints

-dependencies contains between 1 and 30 elements, inclusive.
-Each element of dependencies contains between 0 and 50 characters, inclusive.
-Each element of dependencies is a space delimited list of integers.
-Each integer in dependencies is between 0 and the number of elements in dependencies - 1, inclusive, and contains no extra leading zeros.
-Each element of dependencies contains no duplicate values.
-If element i of dependencies contains the value j, then element j of dependencies contains the value i.
-Element i of dependencies does not contain the value i.
 

Examples

0)
    
{"1 2", "0", "0", ""}
Returns: {1, 3, 4 }
The example from the problem statement.
1)
    
{"1 2", "0 2", "0 1"}
Returns: {3 }
We have to take all three machines.
2)
    
{"","","",""}
Returns: {1, 2, 3, 4 }
We can take any number of these machines since there are no dependencies.
3)
    
{"4 2", "3", "0 4", "1", "0 2", "6", "5"}
Returns: {2, 3, 4, 5, 7 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

StickedWords

Dynamic Programming, Graph Theory



Used in:

SRM 291

Used as:

Division I Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5954

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9812&pm=5954

Problem Statement

    

We have a dictionary of words dict, and we are writing words down in a single line using the following rules. The first written word can be any word from dict. Each subsequent written word must start with the same letter as the last letter of the previous written word, and that shared letter is only written once (see examples). Only words from dict can be used, but each word can be used an unlimited number of times.

Using the rules above, construct the lexicographically earliest line with length greater than or equal to len characters. Return an empty String ("") if such a line cannot be constructed.

 

Definition

    
Class:StickedWords
Method:constructLine
Parameters:String[], int
Returns:String
Method signature:String constructLine(String[] dict, int len)
(be sure your method is public)
    
 

Constraints

-dict will contain between 1 and 50 elements, inclusive.
-Each element of dict will contain between 2 and 50 characters, inclusive.
-Each element of dict will contain only lowercase letters ('a'-'z').
-len will be between 1 and 2500, inclusive.
 

Examples

0)
    
{"salad", "sandwich", "hamburger", "rings"}
35
Returns: "hamburgeringsandwichamburgeringsalad"
The first word in the line is "hamburger". The next word must start with the letter 'r', so we write "rings". Notice that we only write the shared 'r' once, so at this point, the line is "hamburgerings". The rest of the words, in order, are: "sandwich", "hamburger", "rings", and "salad". The resulting line is 36 characters long, and is the lexicographically earliest possible line containing at least 35 characters.
1)
    
{"salad", "hamburger", "rings"}
35
Returns: ""
2)
    
{"aba", "aac", "czz"}
10
Returns: "abababaaczz"
3)
    
{"aarb", "bcb", "bbd", "dzz"}
15
Returns: "aarbcbcbcbcbbdzz"
4)
    
{"abd", "dgga", "abdg", "gga", "gg", "gaader"}
22
Returns: "abdggabdggabdggabdgaader"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

OperationsArrangement

Brute Force, Dynamic Programming, Math



Used in:

SRM 285

Used as:

Division II Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5952

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8082&pm=5952

Problem Statement

    

You are given a sequence of digits. You must insert either a '+' (addition) operator or a '*' (multiplication) operator between each pair of adjacent digits in such a way that minimizes the value of the resulting expression. The expression should be evaluated using the standard order of operations (multiplication has a higher precedence than addition).

You will be given a String sequence. Perform the procedure described above on the sequence and return the resulting expression. If there are several possible answers, return the one that comes first lexicographically. Note that '*' comes before '+' lexicographically.

 

Definition

    
Class:OperationsArrangement
Method:arrange
Parameters:String
Returns:String
Method signature:String arrange(String sequence)
(be sure your method is public)
    
 

Constraints

-sequence will contain between 2 and 50 characters, inclusive.
-Each character in sequence will be a digit ('0'-'9').
 

Examples

0)
    
"222"
Returns: "2*2+2"
The minimal result can be obtained in three ways: "2*2+2", "2+2*2" and "2+2+2". The first one comes first lexicographically.
1)
    
"322"
Returns: "3+2*2"
2)
    
"307"
Returns: "3*0*7"
3)
    
"391118571"
Returns: "3+9*1*1*1+8+5+7*1"
4)
    
"111221911212"
Returns: "1*1*1*2*2*1+9*1*1+2*1*2"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Distincter

Graph Theory



Used in:

SRM 285

Used as:

Division I Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5951

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8082&pm=5951

Problem Statement

    

We are given a int[] sequence containing a sequence of numbers. In a single operation, we can either increment or decrement the value of a single element by 1. Determine the minimum number of operations we must perform before the sequence contains at least K distinct elements.

 

Definition

    
Class:Distincter
Method:disperse
Parameters:int[], int
Returns:int
Method signature:int disperse(int[] sequence, int K)
(be sure your method is public)
    
 

Notes

-Note that we can create negative elements during the process.
 

Constraints

-sequence will contain between 1 and 50 elements, inclusive.
-Each element in sequence will be between 1 and 1000, inclusive.
-K will be between 1 and the number of elements in sequence, inclusive.
 

Examples

0)
    
{5, 1, 3}
2
Returns: 0
The sequence already has two distinct elements.
1)
    
{1, 1, 1, 1, 1, 1, 1}
5
Returns: 6
Some elements can become negative.
2)
    
{1, 1, 1, 1, 1, 2, 3}
6
Returns: 6
3)
    
{8, 9, 7, 8, 7, 9, 7}
7
Returns: 7
4)
    
{1, 2, 3, 4, 4, 5, 7, 7, 8}
9
Returns: 4
The optimal way to make 9 distinct elements is to increase one of the 4s two times and increase one of the 7s two times.
5)
    
{576, 571, 571, 572, 575, 572, 571, 568, 573, 572, 569, 572}
11
Returns: 12

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FunctionDependency

Sorting



Used in:

SRM 276

Used as:

Division II Level Three

Writer:

timmac

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5942

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8073&pm=5942

Problem Statement

    

You are developing a database platform that supports, among other things, user defined functions. User-defined functions may call internal functions, other user-defined functions, or both. A user-defined function, FuncA, is said to be dependent on another function, FuncB, if it calls FuncB.

You have been tasked with writing a module that will "script" (list out the code for) all of the functions in a given database. However, because of dependency issues, they must be scripted in a specific order that meets the following criteria:

  • A function cannot be scripted until all of its dependent functions have already been scripted.
  • Whenever more than one function could be scripted (subject to the first requirement), the one whose name occurs first lexicographically will be scripted first.

You are given a String[] funcs, each element of which is the name of a function in the database. You are also given a String[] depends, a list describing the dependency of each function. Each element of depends is a space-delimited list of integers. Each element of depends corresponds to the element of funcs with the same index. Each number represented in each element of depends refers to the 0-based index of another function.

For instance, suppose a database has two functions, A and B, each of which is dependent on a third function, C. The input might then be given by:

{"B", "C", "A"}
{"1", "", "1"}

Now, since functions A and B both depend upon C, we have to script C first. After that, either A or B could be scripted, since C has already been scripted. We use the second rule to determine that we should script A first. Our return is thus:

{"C", "A", "B"}

You are to return a String[] containing the names of the functions in the order in which they should be scripted.

 

Definition

    
Class:FunctionDependency
Method:scriptingOrder
Parameters:String[], String[]
Returns:String[]
Method signature:String[] scriptingOrder(String[] funcs, String[] depends)
(be sure your method is public)
    
 

Constraints

-funcs will contain between 1 and 50 elements, inclusive.
-depends will contain the same number of elements as funcs.
-Each element of funcs will contain between 1 and 50 upper case ('A'-'Z') character, inclusive.
-Each element of depends will be a space-delimited list of integers, with no leading zeroes.
-Each integer represented in depends will be between 0 and n-1, inclusive, where n is the number of elements in funcs.
-There will be no circular dependencies.
 

Examples

0)
    
{"B", "C", "A"}
{"1", "", "1"}
Returns: {"C", "A", "B" }
The example from the problem statement.
1)
    
{"B", "C", "A"}
{"1", "", "0"}
Returns: {"C", "B", "A" }
2)
    
{"K", "A", "B", "C", "D", "E", "F", "G", "H", "I"}
{"", "", "1 1", "2", "3", "4", "5", "6", "7", "8"}
Returns: {"A", "B", "C", "D", "E", "F", "G", "H", "I", "K" }
Careful! It is permissible for the same dependency to be listed twice.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

UnitsMoving

Graph Theory



Used in:

SRM 278

Used as:

Division I Level Three

Writer:

Vedensky

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5921

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8075&pm=5921

Problem Statement

    You are to write a procedure for a computer game that will move groups of units.



You are given a String[] start containing the starting positions of all the units. Each element is formatted as "X Y V", where (X, Y) are integer coordinates, and V is an integer velocity in meters per second. You are also given a String[] finish containing the ending positions for all the units. Each element is formatted as "X Y", where (X, Y) are integer coordinates, and each element is distinct from the other elements. The ith element of start represents a single unit which must be moved from the coordinates in start[i] to the coordinates in some element of finish at the velocity given in start[i]. Each unit must be moved to a different location (that means, each two different units from start must be moved to different ending positions). Return a double representing the minimal time (in seconds) in which all the units will reach their destinations.
 

Definition

    
Class:UnitsMoving
Method:bestTime
Parameters:String[], String[]
Returns:double
Method signature:double bestTime(String[] start, String[] finish)
(be sure your method is public)
    
 

Notes

-The returned value must be accurate to 1e-9 relative or absolute.
 

Constraints

-start will contain between 1 and 50 elements, inclusive.
-finish will contain the same number of elements as start.
-Each element of start will be formatted as "X Y V", where X, Y and V are integers without leading zeroes.
-Each element of finish will be formatted as "X Y", where X and Y are integers without leading zeroes.
-All X and Y will be between 0 and 1000, inclusive.
-All V will be between 1 and 10, inclusive.
-All elements of finish will be different.
 

Examples

0)
    
{"0 0 1", "0 1 1"}
{"1 1", "1 0"}
Returns: 1.0
The first unit moves to the second location for 1 second, and the second unit moves to the first location also for 1 second.
1)
    
{"0 0 1", "0 1 1"}
{"1 1", "2 1"}
Returns: 2.0
In this case, it is better to move the fist unit to the first location and the second unit - to the second one.
2)
    
{"0 0 1", "5 0 1"}
{"5 12", "10 12"}
Returns: 13.0
3)
    
{"0 0 2", "5 0 1"}
{"5 12", "10 12"}
Returns: 12.0
4)
    
{"308 994 10", "157 22 9", "282 975 5", "993 17 8", "925 771 2", "843 110 6", 
"860 629 8", "947 143 6", "921 348 7", "520 607 6", "735 306 3",
"253 861 7", "562 56 9", "243 168 2", "521 971 1", "745 537 7"}
{"431 911", "109 951", "177 721", "295 831", "937 256", "608 180", "863 994", "148 406",
"275 531", "635 297", "681 404", "909 151", "569 730", "332 391", "94 97", "376 142"}
Returns: 115.72920979597156

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GreenWave

Brute Force, Simulation



Used in:

SRM 289

Used as:

Division II Level Three

Writer:

esteban

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5920

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9810&pm=5920

Problem Statement

    

A new road has been opened. It is L meters long, and it is divided into one-meter sections called positions. There are traffic lights at various positions on the road. If there's a traffic light at position i, it means that a car at position i must wait until the light is green before it can proceed to position i+1. Traffic lights are either red or green, and they change every five seconds.

There are some cars waiting to enter into the road. Each car is one meter long, and there can never be more than one car at a single position of the road. Once a car enters the road it cannot overtake other cars. The cars' speeds are given in the int[] speeds, where the i-th element is the speed of the i-th car. Each traffic light starts out red, but the duration of that first red light varies between one and five seconds, inclusive. Then, the five second cycle starts. The initial red light duration may be different for each traffic light.

Suppose that the road goes from left to right. The cars move as follows:

  • Step 1: Each car already in the road (from right to left) tries to move rightward as many positions as its speed indicates, but it can be blocked by another car or a red traffic light (here rightward means increasing its position).

    Then, if position 0 of the road is free, the car with the lowest index in speeds that has not yet entered the road enters at position 0, without moving.

    This step takes one second.
  • Step 2: The traffic lights are updated, if necessary. This step takes no time.
  • Step 3: If all the cars have left the road, stop, otherwise go to Step 1.

You are given L, the road length, speeds, the speed of each car, and lights, the position of each traffic light. Determine the duration of the first red light for each traffic light that minimizes the total time it takes for all the cars to leave the road (that is, the number of seconds elapsed until the last car leaves the road). Return a int[], where the i-th element is the duration of the first red light of the i-th traffic light. If two solutions give the same time, return the one that comes first lexicographically.

 

Definition

    
Class:GreenWave
Method:getFirstRed
Parameters:int, int[], int[]
Returns:int[]
Method signature:int[] getFirstRed(int L, int[] speeds, int[] lights)
(be sure your method is public)
    
 

Notes

-When a car leaves the road (by moving past the rightmost position on the road), it can no longer block the other cars.
-Solution A comes earlier than B lexicographically if A has a lower value than B in the first position at which they differ.
 

Constraints

-L will be between 1 and 500, inclusive.
-speeds will contain between 0 and 10 elements, inclusive.
-Each element of speeds will be between 1 and 30, inclusive.
-lights will contain between 0 and 5 elements, inclusive.
-Each element of lights will be between 0 and L-2, inclusive.
-All the elements of lights will be distinct.
 

Examples

0)
    
10
{1}
{0}
Returns: {1 }
Second 1: There are initially no cars in the road. Since position 0 is unoccupied, the car is able to enter the road.

Second 2: The traffic light has just turned green. The car can move right to position 1.

Second 10: The car moves from position 8 to position 9 (the last position on the road).

Second 11: The car leaves the road.

1)
    
50
{1}
{4, 5, 6, 7, 8}
Returns: {1, 2, 3, 4, 5 }
2)
    
300
{2, 1}
{16}
Returns: {4 }
When the duration of the first red light is 4 seconds, neither car will ever be blocked by a red light.
3)
    
300
{1, 2}
{16}
Returns: {3 }
Although the second car has to wait for the traffic light for one second, it is fast enough to catch up with the first one.
4)
    
60
{12, 15, 20}
{58}
Returns: {1 }
Remember that once a car leaves the road, it no longer blocks the other cars.
5)
    
340
{16, 15, 29, 7, 9, 15, 2}
{125, 156, 274, 309, 211}
Returns: {5, 1, 1, 1, 1 }
6)
    
494
{11, 7, 11, 6}
{438, 251}
Returns: {3, 1 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SafeJourney

Geometry, Graph Theory



Used in:

SRM 277

Used as:

Division I Level Three

Writer:

lovro

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5918

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8074&pm=5918

Problem Statement

    

Note: examples in this problem statement contain images which may not display properly if viewed outside the applet.

John lives in a large city and commutes to work every day. Afraid of getting hit by cars, he tends to plot his routes so that he crosses as few roads as possible, leaving home earlier if necessary. John crosses a road whenever his path intersects the road. He'll never walk along the road (on it), since that would be dangerous.

When modeled in a plane, the city is width units wide and length units long. John may never leave the city at any time. More precisely, his x-coordinate must be between 0 and width (inclusive) and his y-coordinate between 0 and length (inclusive) at all times.

You will be given the description of roads (horizontal and vertical line segments) in the city. Horizontal roads will be formatted as "y x1 x2" (quotes for clarity), vertical roads as "x y1 y2". You will also be given the coordinates of John's home and workplace, each formatted as "x y".

Return the minimum number of roads John needs to cross in order to get from home to work.

 

Definition

    
Class:SafeJourney
Method:fewestRoadCrossings
Parameters:int, int, String[], String[], String, String
Returns:int
Method signature:int fewestRoadCrossings(int width, int length, String[] horizontal, String[] vertical, String home, String work)
(be sure your method is public)
    
 

Notes

-Crossing an intersection of two roads (one horizontal and one vertical) diagonally counts as crossing two roads.
 

Constraints

-width and length will be between 1 and 2,000,000,000, inclusive.
-horizontal and vertical will each contain between 0 and 50 elements, inclusive.
-Each element of horizontal and vertical will be at most 50 characters long and will contain a comma-separated list of roads with at least one road.
-Each road in horizontal will be formatted as "y x1 x2", where x1 is less than x2.
-Each road in vertical will be formatted as "x y1 y2", where y1 is less than y2.
-home and work will both be formatted as "x y".
-All x-coordinates will be between 0 and width, inclusive, and all y-coordinates will be between 0 and length, inclusive.
-All numbers will be integers with no leading zeros.
-No two roads in horizontal will overlap and no two roads in vertical will overlap, although they may have common endpoints.
-Neither home nor work will lie on a road, on either of a road's endpoints, or on the boundary of the city.
 

Examples

0)
    
6
4
{ "2 0 6" }
{ "2 2 4", "4 0 2" }
"1 3"
"5 1"
Returns: 2
John can't get to work without crossing at least two roads.

1)
    
6
4
{ "2 0 6" }
{ "2 0 2", "4 2 4" }
"1 3"
"5 1"
Returns: 1
The vertical roads have moved and John now needs to cross only one road.

2)
    
4
5
{ "4 1 3,1 1 3" }
{ "2 1 4" }
"1 2"
"3 3"
Returns: 0
3)
    
7
8
{ "2 0 7", "4 0 7", "5 2 4,5 5 6", "6 0 4,6 5 7", "7 1 3" }
{ "2 2 5", "3 0 6", "4 0 7", "5 0 5" }
"1 3"
"6 1"
Returns: 4
4)
    
5
5
{ }
{ "3 0 2", "3 2 5" }
"2 4"
"4 1"
Returns: 1
Roads will not overlap, but may have common endpoints. There is no way of getting from home to work without crossing at least one of the roads.
5)
    
100
100
{ "10 0 100,20 0 100,30 0 100,40 0 100,50 0 100",
  "60 0 100,70 0 100,80 0 100,90 0 100" }
{ "10 0 100,20 0 100,30 0 100,40 0 100,50 0 100",
  "60 0 100,70 0 100,80 0 100,90 0 100" }
"15 6"
"93 95"
Returns: 17
6)
    
13
9
{ "7 0 5,6 0 5,4 4 8,4 9 13,3 4 13,2 4 8,3 1 3" }
{ "1 1 3,3 0 3,4 2 7,5 2 7,7 5 9,8 5 9,8 0 1,9 1 3", "10 1 3" }
"2 8"
"2 1"
Returns: 1
7)
    
15
8
{ "1 9 14", "4 0 2", "6 2 3", "6 9 12", "7 0 2", "7 7 14" }
{ "3 0 7", "4 1 8", "7 0 7", "9 1 6", "12 4 6", "14 1 6" }
"10 4"
"1 2"
Returns: 0

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GreedyGovernment

Graph Theory, Recursion, Search, String Manipulation



Used in:

SRM 275

Used as:

Division II Level Three

Writer:

NeverMore

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5910

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8072&pm=5910

Problem Statement

    You live in a town which is divided into sectors, numbered 0 through N-1. In addition, some sectors are connected by roads. You must pay a toll to move between sectors. The government of your town is rather greedy, and it has decided to increase the toll along one of these roads. In particular, they are going to increase the toll along a road by tollHike dollars, such that the average cost of travelling from sector 0 to sector N-1 is maximized. This average cost is determined as the average cost over all distinct valid paths from sector 0 to sector N-1. Two paths from sector 0 to sector N-1 are distinct if they either visit a different number of sectors or visit sectors in a different order. A path is valid if it does not take you through any sector more than once while travelling from sector 0 to N-1.



Create a class GreedyGovernment which contains a method maxAverageCost. You will be given a String[] tolls and an int tollHike as arguments. The j'th character in the i'th element of tolls indicates the toll to travel between sectors i and j. If the j'th character in the i'th element of tolls is an 'X', then it is not possible to travel from sector i to sector j (although you may still be able to travel from sector j to sector i). If there is no way to travel from sector 0 to sector N-1, your method should return 0. Otherwise, the method should return a double corresponding to the maximum average cost that the government can expect.
 

Definition

    
Class:GreedyGovernment
Method:maxAverageCost
Parameters:String[], int
Returns:double
Method signature:double maxAverageCost(String[] tolls, int tollHike)
(be sure your method is public)
    
 

Notes

-Your return value must have an absolute or relative error less than 1e-9.
 

Constraints

-tolls will contain between 2 and 10 elements, inclusive.
-Each element of tolls will contain the same number of characters as the number of elements in tolls.
-Each element of tolls will contain only the characters '1'-'9', inclusive, or the character 'X'.
-The i'th character of the i'th element of tolls will be 'X' for all i.
-tollHike will be between 1 and 100, inclusive.
 

Examples

0)
    
{"X324", "XXX2", "12X5", "991X"}
9
Returns: 10.0
Note that there are 4 ways to travel from sector 0 to sector 3:

sector 0 --> sector 3

sector 0 --> sector 1 --> sector 3

sector 0 --> sector 2 --> sector 3

sector 0 --> sector 2 --> sector 1 --> sector 3



Any other path from sector 0 to sector 3 (for example, sector 0 --> sector 2 --> sector 0 --> sector 3) visits a sector more than once, which is not allowed in your town.
1)
    
{"X324", "5X22", "12X5", "991X"}
57
Returns: 29.2
2)
    
{"X11", "2X1", "37X"}
76
Returns: 39.5
3)
    
{"X32X", "XXXX", "XXXX", "XXXX"}
99
Returns: 0.0
There is no way to travel from sector 0 to sector 3.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DyckwordUniformer

Brute Force, Recursion, Sorting



Used in:

SRM 274

Used as:

Division I Level Two

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5887

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8071&pm=5887

Problem Statement

    

A Dyck word is a string consisting of n X's and n Y's (for some positive integer n) such that no initial segment of the string has more Y's than X's.

If we have a Dyck word we can swap any two consecutive substrings when both of them are Dyck words. It is easy to show that the result of this swap operation is a Dyck word too. For example, in "XXYXXYYY" (quotes for clarity) we can swap the substrings "XY" and "XXYY" to get "XXXYYXYY".

If a Dyck word A can be obtained from a Dyck word B using some number of the described swap operations they are called equivalent.

You will be given a String dyckword. Return the lexicographically smallest (i.e., the one that occurs first in alphabetical order) Dyck word that is equivalent with the given dyckword. Return "" (the empty string) if the given string is not a Dyck word.

 

Definition

    
Class:DyckwordUniformer
Method:uniform
Parameters:String
Returns:String
Method signature:String uniform(String dyckword)
(be sure your method is public)
    
 

Constraints

-dyckword will contain between 2 and 50 characters, inclusive.
-Each character in dyckword will be either 'X' or 'Y'.
 

Examples

0)
    
"XXYXXYYY"
Returns: "XXXYYXYY"
The example from the problem statement.
1)
    
"XYXYXXXYYYXXYY"
Returns: "XXXYYYXXYYXYXY"
The result can be obtained by four swaps "XYXYXXXYYYXXYY" -> "XYXXXYYYXYXXYY" -> "XXXYYYXYXYXXYY" -> "XXXYYYXYXXYYXY" -> "XXXYYYXXYYXYXY".
2)
    
"XXXYYYXXYXXXYYYY"
Returns: "XXXXYYYXYYXXXYYY"
The result can be obtained by two swaps "XXXYYYXXYXXXYYYY" -> "XXXYYYXXXXYYYXYY" -> "XXXXYYYXYYXXXYYY".
3)
    
"XXYYYX"
Returns: ""

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PalindromeMaker

Brute Force, Sorting



Used in:

SRM 274

Used as:

Division I Level One , Division II Level Two

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5881

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8071&pm=5881

Problem Statement

    

A palindrome is a string that is spelled the same forward and backward. We want to rearrange letters of the given string baseString so that it becomes a palindrome.

You will be given a String baseString. Return the palindrome that can be made from baseString. When more than one palindrome can be made, return the lexicographically earliest (i.e., the one that occurs first in alphabetical order). Return "" (the empty string) if no palindromes can be made from baseString.

 

Definition

    
Class:PalindromeMaker
Method:make
Parameters:String
Returns:String
Method signature:String make(String baseString)
(be sure your method is public)
    
 

Constraints

-baseString will contain between 1 and 50 characters, inclusive.
-Each character in baseString will be an uppercase letter ('A'-'Z').
 

Examples

0)
    
"AABB"
Returns: "ABBA"
1)
    
"AAABB"
Returns: "ABABA"
2)
    
"ABACABA"
Returns: "AABCBAA"
3)
    
"ABCD"
Returns: ""

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SwapSorter

Graph Theory



Used in:

SRM 279

Used as:

Division I Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5874

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8076&pm=5874

Problem Statement

    

The organization of an array A is computed as follows: Create an array B containing the exact same elements as A, but sorted in non-descending order. Count the number of distinct values for i such that A[i] is equal to B[i]. This value is the organization of the array A. For example, the organization of { 2, 1, 1, 3 } is 2 because the second and fourth elements are not changed after sorting.

Two elements may be swapped only if the organization of the array would increase as a result of the swap.

You will be given a int[] arrayData. Return the maximal number of the swap operations that can be performed.

 

Definition

    
Class:SwapSorter
Method:maximizeSwaps
Parameters:int[]
Returns:int
Method signature:int maximizeSwaps(int[] arrayData)
(be sure your method is public)
    
 

Constraints

-arrayData will have between 1 and 50 elements, inclusive.
-Each element of arrayData will be between 1 and 1000, inclusive.
 

Examples

0)
    
{2, 1, 1, 3}
Returns: 1
The only possible swap is {2, 1, 1, 3} -> {1, 1, 2, 3}
1)
    
{7, 5, 3, 4}
Returns: 3
{7, 5, 3, 4} -> {3, 5, 7, 4} -> {3, 4, 7, 5} -> {3, 4, 5, 7}
2)
    
{2, 1, 4, 3}
Returns: 2
{2, 1, 4, 3} -> {1, 2, 4, 3} -> {1, 2, 3, 4}
3)
    
{1, 7, 8, 12, 17, 19, 21, 23, 24, 25, 26, 27, 35}
Returns: 0
The array is already sorted.
4)
    
{2, 3, 3, 1, 1, 2}
Returns: 5
5)
    
{2, 3, 4, 1, 7, 7, 5, 5, 8, 7, 10, 10, 10, 9, 9, 9}
Returns: 11

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DrawPlanar

Brute Force, Graph Theory, Recursion



Used in:

SRM 280

Used as:

Division I Level Three

Writer:

lars2520

Testers:

PabloGilberto , Yarin , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4846

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8077&pm=4846

Problem Statement

    We all know that a planar graph is one that you can draw without having any edges crossing. Perhaps less well known is that a planar graph can always be drawn with vertices on lattice points and with edges as straight lines between connected vertices.



You will be given a String[], graph, representing a planar undirected graph, where the jth character of element i of graph indicates whether vertices i and j are connected ('T' for true, 'F' for false). Your task is to find the area of the smallest rectangular box that the vertices can be placed in so that they are located on lattice points with non-overlapping straight edges between connected vertices.
 

Definition

    
Class:DrawPlanar
Method:minArea
Parameters:String[]
Returns:int
Method signature:int minArea(String[] graph)
(be sure your method is public)
    
 

Notes

-Lattice points are ones with integer coordinates.
 

Constraints

-graph will contain between 1 and 7 elements, inclusive.
-Each element of graph will contain the same number of characters as there are elements in graph.
-Each character in graph will be 'T' or 'F'.
-Character i in element i of graph will be 'F'.
-Character i in element j of graph will be equal to character j in element i.
-The graph will be planar.
 

Examples

0)
    
{"F"}
Returns: 0
With just one vertex, a single point suffices to draw the graph, so the area is 0.
1)
    
{"FTF",
 "TFF",
 "FFF"}
Returns: 0
In this case, we can draw the vertices all in a line, again with area 0.
2)
    
{"FTT",
 "TFT",
 "TTF"}
Returns: 1
Here, we can select any three corners of a 1x1 square.
3)
    
{"FTTT",
 "TFTT",
 "TTFT",
 "TTTF"}
Returns: 4
4)
    
{"FTTTTTT",
 "TFTTTFT",
 "TTFFFFT",
 "TTFFTFF",
 "TTFTFTT",
 "TFFFTFT",
 "TTTFTTF"}
Returns: 15

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AirlinerSeats

Greedy



Used in:

SRM 277

Used as:

Division I Level Two

Writer:

lovro

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4828

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8074&pm=4828

Problem Statement

    

Note: this problem statement contains an image that may not display properly if viewed outside the applet.

When on a long flight, it is often helpful to be in an aisle seat (a seat adjacent to an aisle). This way you don't need to bother another passenger when you need to go to the restroom or take a walk. However, because large airliners are built to hold as many passengers as possible, only a limited number of seats can be aisle seats.

A typical arrangement of 10 seats in a single row with 2 aisles is as follows:

Aisle seats are colored green in the above example (there are four such seats), while center and window seats are colored orange.

All of the seats are equally wide and each aisle has the same width as a single seat. If an airplane's row is wide enough to fit width seats or aisles, and the airline wants exactly seats seats to be fitted in a row, find the arrangement which maximizes the number of aisle seats. A row should be formatted as a string of characters so that seats and aisles are represented by 'S' and '.' (dot) characters, respectively. If there are multiple arrangements which maximize the number of aisle seats, find the lexicographically smallest one (the dot character comes before 'S' in the lexicographical order).

You are to return the required arrangement (or part of it) as a String[] containing no more than 2 Strings:

  • If width is 50 or less, return the entire arrangement as a single String inside the String[].
  • If width is between 51 and 100 (inclusive), return the entire arrangement as two Strings, split after the first 50 characters.
  • If width is more than 100, return two Strings containing the first and last 50 characters of the arrangement, respectively.

 

Definition

    
Class:AirlinerSeats
Method:mostAisleSeats
Parameters:int, int
Returns:String[]
Method signature:String[] mostAisleSeats(int width, int seats)
(be sure your method is public)
    
 

Constraints

-width will be between 1 and 100000, inclusive.
-seats will be between 0 and width, inclusive.
 

Examples

0)
    
6
3
Returns: {"..SS.S" }
All three seats can be made aisle seats and this is the lexicographically smallest such arrangement.
1)
    
6
4
Returns: {"S.SS.S" }
This is the only arrangement where all four seats are aisle seats.
2)
    
12
10
Returns: {"S.SS.SSSSSSS" }
The picture in the problem statement shows another arrangement with the maximum number of aisle seats, but this one is lexicographically smaller.
3)
    
11
7
Returns: {".SS.SS.SS.S" }
4)
    
52
52
Returns: {"SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", "SS" }
5)
    
200
2
Returns: 
{"..................................................",
"...............................................S.S" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CaterpillarTree

Graph Theory, Recursion



Used in:

TCO05 Wildcard

Used as:

Division I Level One

Writer:

Yarin

Testers:

PabloGilberto , lbackstrom , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4818

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8095&pm=4818

Problem Statement

    

A caterpillar tree is a tree in which every node is on a central stalk or only one graph edge away from the stalk. The figure below illustrates to the left a caterpillar tree with 14 nodes (the stalk marked in blue), and on the right a non-caterpillar tree with 9 nodes.



Given the description of a tree, determine the least number of nodes that must be removed for the tree to become a caterpillar tree. The tree will be described as a string of 0's and 1's. Starting from some node in the tree, a '1' in the string traverses the tree to a previously unvisited node, while a '0' backtracks to the previous node. The trees in the figure above would be described as "11101011111010010001000100" and "1111100100110000", respectively, if the traversals starts at node 1 and the nodes are visited in the numbered orders.

Create a class CaterpillarTree containing the method fewestRemovals which takes a String[] tree containing the description of the tree (concatenate the elements to get the full description), and returns an int containing the fewest number of nodes that must be removed for the tree to become a caterpillar tree.

 

Definition

    
Class:CaterpillarTree
Method:fewestRemovals
Parameters:String[]
Returns:int
Method signature:int fewestRemovals(String[] tree)
(be sure your method is public)
    
 

Constraints

-tree will contain between 1 and 50 elements, inclusive.
-Each element in tree will only contain the characters '0' and '1'.
-Each element in tree will contain between 1 and 50 characters, inclusive.
-tree will describe a valid tree.
 

Examples

0)
    
{"11101011111010010001000100"}
Returns: 0
This is the leftmost picture above. Since it already is a caterpillar tree, no nodes have to be removed.
1)
    
{"1111100100110000"}
Returns: 1
This is the rightmost picture. One of the leaf nodes to the left must be removed for it to become a caterpillar tree.
2)
    
{"1111100000",
 "1111100000",
 "1111100000",
 "1111100000",
 "1111100000"}
Returns: 12
This is a star graph, with one node in the center and five arms containing five nodes each. If we delete four of the five nodes in three of the arms, we end up with a graph that is a caterpillar tree.
3)
    
{"1","0"}
Returns: 0
4)
    
{"11110100111100100111100110100110001110101001111000",
 "1101100000011100110000111001101100010000"}
Returns: 23

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RingCount

Graph Theory, Recursion



Used in:

TCO05 Semi 2

Used as:

Division I Level One

Writer:

lars2520

Testers:

PabloGilberto , Yarin , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4779

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8092&pm=4779

Problem Statement

    If you look at a cross section of a tree you will notice that there are several rings in it. The innermost ring represents the first year of the tree's growth, and each year the tree adds one new ring. You will be given a bitmap of a tree's cross section. Character j of element i represents the pixel at position (j,i) and is either an 'X' or an '.'. The exact structure of the rings can be defined recursively. The innermost ring consists of a group of connected 'X's. The innermost ring is then surrounded by '.' characters, which are then surrounded by 'X' characters. Each ring after is formed in the same way: all previous rings are surrounded by '.' characters, which are then surrounded by 'X' characters. The group of '.' characters that surround previous rings are all connected in a circle (horizontally or vertically), as are the 'X' characters forming the new ring. The background of the image also consists of '.' characters, and there may be no 'X's on the edges of the image. For example, the following is a valid bitmap with 2 rings:
    {".........",
     ".XXXXXXX.",
     ".X....XX.",
     ".X.XX.X..",
     ".X....XX.",
     ".XXXXXXX.",
     "........."}
If the bitmap represents an image of rings as defined above, you are to return the number of rings in it (only the 'X's make rings). Otherwise, if the image is not valid in some way, you are to return -1.
 

Definition

    
Class:RingCount
Method:count
Parameters:String[]
Returns:int
Method signature:int count(String[] bitmap)
(be sure your method is public)
    
 

Notes

-Informally, a ring is connected in a circle if, for every pair of pixels in that ring, there is a path (of horizontal and vertical steps to pixels in the ring) going from one pixel to the other both in both clockwise and counterclockwise directions.
 

Constraints

-bitmap will contain between 1 and 50 elements, inclusive.
-Each element of bitmap will contain the same number of characters.
-Each element of bitmap will contain between 1 and 50 characters.
-Each character in bitmap will be 'X' or '.'.
 

Examples

0)
    
{".........",
 ".XXXXXXX.",
 ".X....XX.",
 ".X.XX.X..",
 ".X....XX.",
 ".XXXXXXX.",
 "........."}
Returns: 2
1)
    
{"...",
 ".X.",
 "..."}
Returns: 1
2)
    
{"...........",
 ".XXXXXXXXX.",
 ".X.......X.",
 ".X.XXXXX.X.",
 ".X.X...X.X.",
 ".X.X..XX.X.",
 ".X.X...X.X.",
 ".X.XXXXX.X.",
 ".X.......X.",
 ".XXXXXXXXX.",
 "..........."}
Returns: -1
This is invalid because there is no innermost ring consisting of just 'X's.
3)
    
{".......",
 ".XXXXX.",
 ".X...X.",
 ".X.X.X.",
 ".X...X.",
 ".XXXX..",
 "......."}
Returns: -1
The rings of 'X's and '.'s must be horizontally and vertically connected in a circle. In this example, the large ring of 'X's is connected, but not in a circle.
4)
    
{"X"}
Returns: -1
There may be no 'X's on the edges.
5)
    
{
".........",
".XXXXXXX.",
".X.....X.",
".X.X.X.X.",
".X.....XX",
".XXXXXXX.",
"........."}
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SalesmansDilemma

Dynamic Programming, Graph Theory



Used in:

SRM 270

Used as:

Division I Level Two

Writer:

misof

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4755

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8067&pm=4755

Problem Statement

    

Travelling salesmen (and of course, travelling saleswomen, too) usually have lots of problems. And some of them are pretty hard to solve algorithmically. Let's take a look at one such problem.

In the country there are several towns. Let towns be their count. The towns are numbered from 0 to towns-1. Our travelling salesman wants to travel through this country. He starts his journey in the town origin and wants to end it in the town destination.

There are several means of transportation he may use. For each of them he knows the source and destination town and its cost. Furthermore, each time he enters a town, he will be able to sign some contracts there and make some money. This amount of money may differ from town to town, but for each town it is a fixed amount. He does sign contracts at the beginning of his journey (in the town origin). Of course, the salesman's goal is to maximize the amount of money he has at the end of his journey.

The various travel possibilities are given in a String[] travelCosts, and the profits for each town are given in a int[] profits. Each element of travelCosts is of the form "SOURCE DESTINATION COST", where SOURCE and DESTINATION are town numbers and COST is the cost of using this transportation. In profits there are exactly towns elements, and the i-th of them is the amount of money gained when entering town i.

If it is not possible to reach the destination town at all, return the String "IMPOSSIBLE". If it is possible to reach the destination town with an arbitrarily large final profit, return the String "ENDLESS PROFIT". Otherwise, return the String "BEST PROFIT: X", where X is the best profit he can make. The value X must be printed with no unnecessary leading zeroes.

 

Definition

    
Class:SalesmansDilemma
Method:bestRoute
Parameters:int, int, int, String[], int[]
Returns:String
Method signature:String bestRoute(int towns, int origin, int destination, String[] travelCosts, int[] profits)
(be sure your method is public)
    
 

Notes

-We are interested in the amount the salesman earns during the journey, i.e., the difference between the balance of his account at the end and at the beginning of his journey. This difference may also be negative in case the salesman has to pay more than he earns during his journey.
-The salesman may travel to the same town multiple times. He gains the profit from the town once for each visit he makes.
-All means of transportation can only be used in the specified direction, i.e., they are one-way. The salesman may use each of them multiple times.
 

Constraints

-towns is between 1 and 50, inclusive.
-origin and destination are between 0 and towns-1, inclusive.
-profits has exactly towns elements.
-Each element of profits is between 0 and 1,000,000, inclusive.
-travelCosts has between 1 and 50 elements, inclusive.
-Each element of travelCosts is of the form "SOURCE DESTINATION COST".
-Each SOURCE and DESTINATION in travelCosts are integers between 0 and towns-1, inclusive, with no unnecessary leading zeroes.
-Each COST in travelCosts is an integer between 1 and 1,000,000, inclusive, with no leading zeroes.
 

Examples

0)
    
5
0
4
{"0 1 10", "1 2 10", "2 3 10", "3 1 10", "2 4 10"}
{0, 10, 10, 110, 10}
Returns: "ENDLESS PROFIT"

The profit in each town exactly covers the cost of travelling there. The single exception is town 3. Each time the salesman travels (from town 2) to town 3, he pays 10 for the travel and gains 110 from sales in town 3, resulting in a net gain of 100.

He is able to reach an arbitrarily large profit in the following way: Start by travelling from 0 to 1, travel around the circle 1->2->3->1 sufficiently many times, then travel from 1 to 2 and from 2 to 4.

1)
    
5
0
4
{"0 1 13", "1 2 17", "2 4 20", "0 3 22", "1 3 4747", "2 0 10", "3 4 10"}
{0, 0, 0, 0, 0}
Returns: "BEST PROFIT: -32"
There is no profit here, so the salesman has to find the cheapest way of travelling.
2)
    
3
0
2
{"0 1 10", "1 0 10", "2 1 10"}
{1000, 1000, 47000}
Returns: "IMPOSSIBLE"
The destination town is unreachable.
3)
    
2
0
1
{"0 1 1000", "1 1 10"}
{11, 11}
Returns: "ENDLESS PROFIT"
Loops are allowed.
4)
    
1
0
0
{"0 0 10"}
{7}
Returns: "BEST PROFIT: 7"
Loops are not always useful.
5)
    
5
0
4
{"0 1 13", "1 2 17", "2 4 20", "0 3 22", "1 3 4747", "2 0 10", "3 4 10"}
{8, 10, 20, 1, 100000}
Returns: "BEST PROFIT: 99988"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AreaSplit

Brute Force, Simple Search, Iteration



Used in:

TCO05 Semi 2

Used as:

Division I Level Two

Writer:

gepa

Testers:

PabloGilberto , lbackstrom , Yarin , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4748

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8092&pm=4748

Problem Statement

    

Some square tiles have been selected from a N x M chessboard, building a pattern (not necessarily connected). You have the task of coloring some of the selected tiles red and all of the others blue so that the pattern composed by the blue tiles is a shifted copy of the pattern composed by the red tiles. One example is shown in the figure below (the white tiles in the left image are the selected tiles, which are colored in the right image).

You will be given a String[] board containing N elements, each of them M characters long, with a character '#' indicating that the tile in the corresponding position belongs to the selected tiles (i.e., to be colored, the white tiles in the example above), a character '.' indicating a tile that shall be ignored (the gray tiles in the example above). Return a String[] representing the red pattern, after cropping the image to the smallest rectangle that contains all the red tiles. Use the character '#' to denote tiles painted in red, '.' to denote other tiles. If there are several ways to color the tiles so that two equal patterns are created (one in red, one in blue), use the solution in which the red pattern has the smallest width (horizontal distance from the leftmost red tile to the rightmost red tile). If there are several ways with the smallest width, use the solution among them with the smallest height (vertical distance from the uppermost red tile to the lowermost red tile). If there is still a tie, use the one among the tied ones that comes first lexicographically after you concatenate the Strings representing the solution ('#' comes before '.'). If there is no solution, return an empty String[].

 

Definition

    
Class:AreaSplit
Method:halfPattern
Parameters:String[]
Returns:String[]
Method signature:String[] halfPattern(String[] board)
(be sure your method is public)
    
 

Notes

-Since the red and blue patterns are translated copies of the same pattern, the returned value would be the same if we asked for the blue pattern (since we crop the returned value to the width/height of the resulting pattern).
-All elements of the returned String[] shall have the same length (the width of the red pattern).
 

Constraints

-board will contain between 1 and 50 elements, inclusive.
-Each element of board will have between 1 and 50 characters, inclusive.
-Each character of each element of board will be either '#' or '.'.
-There will be at least one '#' character in at least one element of board.
 

Examples

0)
    
{".........",
 ".##......",
 "..#.##...",
 ".#####...",
 ".#######.",
 ".#..###..",
 "....#....",
 "........."}
Returns: {"##..", ".#..", "####", "###.", "#..." }
The example from the problem statement.
1)
    
{"##",
 "##"}
Returns: {"#", "#" }
Here, two different half-patterns are possible: the horizontal {"##"} (width 2, height 1) and the vertical {"#", "#"} (width 1, height 2). We return the one with the smallest width.
2)
    
{".#..#",
 "##.##"}
Returns: {".#", "##" }
Note that the pattern need not be connected.
3)
    
{".#.##",
 "####.",
 "#...."}
Returns: {"#.##", "#..." }
Even if the pattern is connected, the solution may not be connected.
4)
    
{".###.",
 "##.#.",
 "..###"}
Returns: { }
We can not split this pattern into two equal patterns.
5)
    
{".#.",
 "#.#",
 ".#."}
Returns: {"#.", ".#" }
Here, both {"#.", ".#"} and {".#", "#."} are possible solutions. We have to return the first of these solutions (if we concatenate the two Strings of that solution we get "#..#" which comes lexicographically before ".##.", the concatenation of the Strings of the second solution).

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PatternOptimizer

String Manipulation



Used in:

SRM 269

Used as:

Division I Level One , Division II Level Two

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4717

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8002&pm=4717

Problem Statement

    

Some dictionaries use a word pattern that consists of letters, '?' symbols which each denote exactly one letter, and '*' symbols which each denote zero or more letters.

Interestingly, some patterns represent the same set of words. For example, "*??*a" and "?*?a" (quotes for clarity only) patterns both represent all words that consist of three or more letters and end with 'a'.

You will be given a String pattern. Your method should return the shortest pattern that represents the same set of words as the given pattern. Return the lexicographically first in case of tie.

 

Definition

    
Class:PatternOptimizer
Method:optimize
Parameters:String
Returns:String
Method signature:String optimize(String pattern)
(be sure your method is public)
    
 

Notes

-Note that '*' comes before '?' in the lexicographical order.
 

Constraints

-pattern will contain between 1 and 50 characters, inclusive.
-pattern will contain only letters ('a'-'z', 'A'-'Z'), '?' and '*'.
 

Examples

0)
    
"*??*a"
Returns: "*??a"
1)
    
"*b**a*"
Returns: "*b*a*"
2)
    
"cla??"
Returns: "cla??"
3)
    
"*?*?*?*"
Returns: "*???"
4)
    
"T***nd?*"
Returns: "T*nd*?"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GraphLabel

Brute Force



Used in:

SRM 256

Used as:

Division II Level Three

Writer:

lars2520

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4690

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=7992&pm=4690

Problem Statement

    An undirected graph is defined as a set of vertices with undirected edges connecting some of the pairs of vertices. You will be given such a graph as a String[] where character j of element i is a '1' if and only if vertices i and j are connected. Such a graph has as many vertices in it as there are elements in the String[]. Your task is to assign an integer between 1 and the total number of vertices, inclusive, to each of these vertices. You may not assign the same integer to multiple vertices. Your goal is to assign these integers such that vertices which are connected have integers which are close to each other numerically. More specifically, let max be the maximum difference between the two integers assigned to any two connected vertices. You want to assign the integers to the vertices such that max is minimized. You should return that minimum max.
 

Definition

    
Class:GraphLabel
Method:adjacentDifference
Parameters:String[]
Returns:int
Method signature:int adjacentDifference(String[] graph)
(be sure your method is public)
    
 

Constraints

-graph will contain between 2 and 9 elements, inclusive.
-Each element of graph will contain as many characters as graph has elements.
-Each character in graph will be '0' or '1'.
-Character j of element i of graph will be the same as character i of element j for all i and j.
-Character i of element i of graph will be '0' for all i.
-At least one character in graph will be '1'.
 

Examples

0)
    
{"010000",
 "101111",
 "010111",
 "011010",
 "011101",
 "011010"}
Returns: 3
One way to do this is to assign the label 1 to the first vertex (represented by element 0 of the input), 3 to the second vertex, 4 to the third, 2 to the fourth, 5 to the fifth, and 6 to the sixth.
1)
    
{"01111001",
 "10101000",
 "11000101",
 "10000111",
 "11000111",
 "00111000",
 "00011000",
 "10111000"}
Returns: 4
The labels corresponding to the elements of the input are:

2 1 3 4 5 7 8 6
2)
    
{"011110101",
 "100111000",
 "100000111",
 "110011011",
 "110101001",
 "010110110",
 "101001010",
 "001101101",
 "101110010"}
Returns: 4
3)
    
{"011111111",
 "101111111",
 "110111111",
 "111011111",
 "111101111",
 "111110111",
 "111111011",
 "111111101",
 "111111110"}
 
Returns: 8

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CliqueCount

Brute Force, Graph Theory



Used in:

SRM 256

Used as:

Division I Level Two

Writer:

lars2520

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4687

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=7992&pm=4687

Problem Statement

    An undirected graph is defined as a set of vertices with undirected edges connecting some of the pairs of vertices. A clique in an undirected graph is a non-empty subset of vertices where there is a direct connection between every pair of vertices in the subset. A maximal clique is a clique that is not a proper subset of any other clique. You will be given a graph as a String[] where the jth character of the ith element is a '1' if and only if vertices i and j are connected. Your method should return the number of maximal cliques in the graph.
 

Definition

    
Class:CliqueCount
Method:countCliques
Parameters:String[]
Returns:int
Method signature:int countCliques(String[] graph)
(be sure your method is public)
    
 

Constraints

-graph will contain between 1 and 20 elements, inclusive.
-Each element of graph will contain as many characters as graph has elements.
-Each character in graph will be '0' or '1'.
-Character j of element i of graph will be the same as character i of element j for all i and j.
-Character i of element i of graph will be '0' for all i.
 

Examples

0)
    
{"010",
 "100",
 "000"}
Returns: 2
If the vertices are 0, 1, and 2, corresonding to the elements of the input, then the two maximal cliques are {0,1} and {2}.
1)
    
{"011",
 "101",
 "110"}
Returns: 1
All nodes are connected so there is just one big clique.
2)
    
{"00010000000000100000",
 "00110000000000000000",
 "01011001000000011000",
 "11101000000100010110",
 "00110000001100000000",
 "00000000010000000001",
 "00000000000000011001",
 "00100000000010000001",
 "00000000000100011000",
 "00000100000010000010",
 "00001000000000000010",
 "00011000100001000101",
 "00000001010000000000",
 "00000000000100000010",
 "10000000000000000010",
 "00110010100000000000",
 "00100010100000000000",
 "00010000000100000000",
 "00010000011001100000",
 "00000111000100000000"}
Returns: 28
3)
    
{"00",
 "00"}
Returns: 2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MaxTrip

Graph Theory



Used in:

SRM 268

Used as:

Division I Level Two

Writer:

dgoodman

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4677

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8001&pm=4677

Problem Statement

    You have won a collection of tickets on luxury cruisers. Each ticket can be used only once, but can be used in either direction between the 2 cities printed on the ticket. Your prize gives you free airfare to any city to start your cruising, and free airfare back home from wherever you finish your cruising.

You love to sail and don't want to waste any of your free tickets. How many additional tickets would you have to buy so that your cruise can use all of your tickets?

Create a class MaxTrip that contains a method minBuy that is given Strings portA and portB and that returns the smallest number of additional tickets that can be purchased to allow you to use all of your free tickets. Each position in portA and portB corresponds to one free ticket, allowing you to travel either way between the cities denoted by the corresponding character in portA and in portB.

 

Definition

    
Class:MaxTrip
Method:minBuy
Parameters:String, String
Returns:int
Method signature:int minBuy(String portA, String portB)
(be sure your method is public)
    
 

Constraints

-portA will contain between 1 and 50 characters, inclusive.
-portB will contain the same number of characters as portA.
-portA and portB will contain only uppercase letters ('A'-'Z').
 

Examples

0)
    
"AAX"
"CBY"
Returns: 1
You have 3 free tickets, one between A and C, one between A and B, and one between X and Y. You can use all of these tickets if you purchase one additional ticket. One way is to buy a ticket between C and X. Now your cruise could start at B, go from B to A using your 2nd free ticket, then from A to C using your first free ticket, then from C to X using your purchased ticket, and finally from X to Y using your 3rd free ticket.
1)
    
"AAAAA"
"CBXYQ"
Returns: 2
One plan is to cruise from C to A to B to Q (using a purchased ticket) to A to X to A (using a purchased ticket) to Y.
2)
    
"AB"
"AB"
Returns: 1
Your 2 free tickets are circle cruises that end at the same port that they debark from. To use both of them, you will need to purchase a ticket that goes between A and B.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SequenceOfNumbers

Sorting



Used in:

SRM 255

Used as:

Division II Level One

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4659

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=7228&pm=4659

Problem Statement

    

It is a common mistake to sort numbers as strings. For example, a sorted sequence like {"1", "174", "23", "578", "71", "9"} is not correctly sorted if its elements are interpreted as numbers rather than strings.

You will be given a String[] sequence that is sorted in non-descending order using string comparison. Return this sequence sorted in non-descending order using numerical comparison instead.

 

Definition

    
Class:SequenceOfNumbers
Method:rearrange
Parameters:String[]
Returns:String[]
Method signature:String[] rearrange(String[] sequence)
(be sure your method is public)
    
 

Constraints

-sequence will contain between 2 and 50 elements inclusive.
-Each element of sequence will contain between 1 and 9 characters inclusive.
-Each element of sequence will consist of only digits ('0'-'9').
-Each element of sequence will not start with a '0' digit.
-sequence will be ordered lexicographically.
 

Examples

0)
    
{"1","174","23","578","71","9"}
Returns: {"1", "9", "23", "71", "174", "578" }
1)
    
{"172","172","172","23","23"}
Returns: {"23", "23", "172", "172", "172" }
2)
    
{"183","2","357","38","446","46","628","734","741","838"}
Returns: {"2", "38", "46", "183", "357", "446", "628", "734", "741", "838" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SecurityBunker

Graph Theory



Used in:

SRM 269

Used as:

Division I Level Two

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4650

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8002&pm=4650

Problem Statement

    

You will be given a map of the bunker. The map will consist of bombs ('*'), empty cells ('.') and secret objects ('?') arranged on a regular grid. For security reasons, in case of danger, all secret objects in the bunker should be destroyed by the explosion of any one bomb. A bomb explosion destroys all objects in range D, where D depends on the bomb type. A bomb explosion also causes all other bombs in range D to explode. More formally, an item (a secret object or a bomb) will be affected by a bomb explosion if the distance between the centers of their cells is not greater than D.

You will be given a String[] field. Return the minimal value of D that will ensure that all secret objects will be destroyed by the explosion of any one bomb.

 

Definition

    
Class:SecurityBunker
Method:chooseBomb
Parameters:String[]
Returns:double
Method signature:double chooseBomb(String[] field)
(be sure your method is public)
    
 

Notes

-The returned value must be accurate to 1e-9 relative or absolute.
 

Constraints

-field will contain between 1 and 50 elements, inclusive.
-Each element of field will contain between 1 and 50 characters, inclusive.
-Each element of field will contain the same number of characters.
-field will contain only the characters '*', '.', and '?'.
-field will contain between 1 and 100 '*' characters, inclusive.
-field will contain between 1 and 100 '?' characters, inclusive.
 

Examples

0)
    
{"*.*",
 ".?.",
 "*.*"}
Returns: 1.4142135623730951
The answer is the distance from the secret object to any one of the bombs.
1)
    
{"*****", 
 ".?.?.",
 "..?..",
 ".?.?.",
 "*****"}
Returns: 3.0
With D>=1, the explosion of any bomb will explode all other bombs in the same row.
2)
    
{"*****",
 "....*",
 "....*",
 ".?..*",
 "....*",
 "*...*",
 "*****"}
Returns: 2.23606797749979
3)
    
{"*.*.*.*",
 ".?.?.?."}
Returns: 2.0
D=2 is enough to explode all bombs and the secret objects with them.
4)
    
{"?*..*?....?",
 "...........",
 "....*......",
 "...?.......",
 ".*....**?..",
 "*......?...",
 ".......*...",
 ".......?.*.",
 "..*.......*",
 "?........?.",
 "......?*?.."}
Returns: 5.0

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TheTournament

String Parsing



Used in:

SRM 279

Used as:

Division II Level Two

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4649

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8076&pm=4649

Problem Statement

    

You were hired to manage a forthcoming tournament. Each player will play against each of all the other players. According to the rules, the matches can be played in any order, but the audience will want to know the current leader at any point in time.

You will be given a String[] matches. All elements of matches will be in the form "playerA defeats playerB" (quotes for clarity only). Your method should return the leader after this set of matches. The leader is a player who has played at least one match and has the highest ratio of winning matches to total matches played. In case of a tie, return the player whose name comes first lexicographically. The players' names are case sensitive (i.e. uppercase letters are lexicographically earlier than lowercase letters).

 

Definition

    
Class:TheTournament
Method:findLeader
Parameters:String[]
Returns:String
Method signature:String findLeader(String[] matches)
(be sure your method is public)
    
 

Constraints

-matches will contain between 1 and 50 elements inclusive.
-Each element of matches will be in the form "playerA defeats playerB".
-In each element of matches playerA will differ from playerB.
-There will not be two elements of matches with the same players.
-Each playerA and playerB will contain between 1 and 20 letters ('A'-'Z', 'a'-'z'), inclusive.
 

Examples

0)
    
{"Ted defeats Kate", "Kate defeats Billy", "Ted defeats Billy"}
Returns: "Ted"
Ted wins all his games, but Kate and Billy have at least one defeat.
1)
    
{"Ted defeats Kate", "Kate defeats Billy", "Billy defeats Ted"}
Returns: "Billy"
All players have a 1/2 ratio of wins to total matches, so we should return the player whose name comes first lexicographically.
2)
    
{"Ted defeats Kate", "Kate defeats Billy", "Ted defeats Billy", "Tommy defeats Ted"}
Returns: "Tommy"
Tommy's ratio is 1/1, Kate's and Billy's ratio is 1/2 and Ted's ratio is 1/3. So, Tommy's ratio is the best.
3)
    
{"B defeats BA", "B defeats BB", "BC defeats B", "A defeats AB",
 "A defeats AC", "A defeats AD", "A defeats AE", "AF defeats A",
 "AG defeats A", "AB defeats AF", "AC defeats AG", "BB defeats BC"}
Returns: "A"
4)
    
{"defeats defeats def", "defeats defeats defe", "defe defeats ded", "defeat defeats defeats"}
Returns: "defeat"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SplitSubgraphs

Graph Theory, Recursion



Used in:

TCCC06 Round 2B

Used as:

Division I Level Three

Writer:

AdminBrett

Testers:

PabloGilberto , lbackstrom , Yarin , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4648

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10112&pm=4648

Problem Statement

    A graph is called split if the vertices can be partioned into two non-empty sets A and B such that no two distinct vertices in A are adjacent, and all pairs of distinct vertices in B are adjacent. Considering all possible ways of removing 0 or more nodes from the given graph, return how many of the resulting subgraphs are split. Two subgraphs are considered distinct if the sets of removed nodes are distinct. Character i in element j of graph is '1' if nodes i and j are adjacent, and '0' if not.
 

Definition

    
Class:SplitSubgraphs
Method:howMany
Parameters:String[]
Returns:int
Method signature:int howMany(String[] graph)
(be sure your method is public)
    
 

Constraints

-graph will contain between 1 and 20 elements, inclusive.
-Each character in graph will be '0' or '1'.
-Each element of graph will contain exactly N characters, where N is the number of elements in graph.
-Character i of element i of graph will always be '0'.
-Character i of element j of graph will equal character j of element i.
 

Examples

0)
    
{"011",
 "101",
 "110"
}
Returns: 4
Every subgraph with at least 2 vertices is split.
1)
    
{"0"}
Returns: 0
Note that A and B must both be non-empty.
2)
    
{"0000",
 "0000",
 "0001",
 "0010"
}
Returns: 11
3)
    
{"0100",
 "1000",
 "0001",
 "0010"
}
Returns: 10
4)
    
{"01100",
 "10110",
 "11001",
 "01001",
 "00110"}
Returns: 24

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TriangleRooks

Graph Theory



Used in:

TCO05 Wildcard

Used as:

Division I Level Two

Writer:

AdminBrett

Testers:

PabloGilberto , lbackstrom , Yarin , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4641

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8095&pm=4641

Problem Statement

    Suppose you have half of a chessboard as depicted below with 0 or more rooks placed on it. No two rooks can share a row or column. Beginning with the lower left corner, we travel along the edge of the board. Below, the different positions we move through during this process are numbered.

At each corner, we count how many rooks are above and to the left of our position. Examples illustrating how the rooks are counted are given below.

By travelling from position to position we obtain a sequence of integers. For the above board, our sequence would be
  0, 1, 0, 1, 1, 2, 1, 2, 1, 1, 0.
In this problem we reverse the process. Instead, you are given the sequence and must return the corresponding half-chessboard.



Given a sequence of 2n+1 integers, you will return a String[] with n elements. Element k (0-based), which corresponds to row k of the board, will contain precisely n-k characters. 'R' should be used to denote a rook and '.' should be used to denote an empty square. If more than one board is possible, choose the one where the rook in row 0 is furthest to the left (if such a rook exists). If multiple boards are still possible, choose the one where the rook in row 1 is furthest to the left, and so forth. If no board is possible, return an empty String[]. The sequence will be given in seqBeg and seqEnd. The elements of seqBeg all come before the elements of seqEnd. For example, if
seqBeg = { 0, 1, 0, 1, 1, 2, 1 }
seqEnd = { 2, 1, 1, 0}
then the resulting 11 element input sequence is the same as featured in the example above.
 

Definition

    
Class:TriangleRooks
Method:getBoard
Parameters:int[], int[]
Returns:String[]
Method signature:String[] getBoard(int[] seqBeg, int[] seqEnd)
(be sure your method is public)
    
 

Constraints

-seqBeg and seqEnd will contain between 0 and 50 elements inclusive.
-The combination of seqBeg and seqEnd will contain an odd number of elements.
-The combination of seqBeg and seqEnd will contain at least 3 elements.
-Each element of seqBeg and seqEnd will be between 0 and 100 inclusive.
 

Examples

0)
    
{ 0, 1, 0, 1, 1, 2, 1 }
{ 2, 1, 1, 0}
Returns: {".R...", "...R", "..R", "..", "R" }
From the problem statement.
1)
    
{0,2,2,3,2,2,1,1,0}
{}
Returns: { }
2)
    
{}
{1, 1, 1}
Returns: { }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MusicCompilation

Greedy, Sorting



Used in:

SRM 251

Used as:

Division I Level Three

Writer:

dimkadimon

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4625

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=7226&pm=4625

Problem Statement

    

Over the years you have collected a great mass of music from various artists. These days you have very little time to listen to your whole collection. You decide to make a single compilation that contains the best hits from each artist. Your first attempt at the compilation was to place the best hits in a random order. However, this resulted in songs from the same artist being close or even next to each other. This is highly undesirable since you hate listening to the same artist over and over again.

After some further consideration you realize that there must be some kind of an ultimate order - i.e., an order where artists are 'spread out' across the compilation as much as possible. You then come up with a distance metric (D) that measures the 'spread' of artists across the compilation:

D(compilation) = Sum of all D(i), where D(i) is the distance of the song at position i.

D(i) = k-i, where k is the smallest integer greater than i, such that the songs at positions k and i are by the same artist. 0 if no such k exists.

Each element in artists will be formatted as "<artist name> <number of hits>". Your task is to make a String[] compilation of these artists such that D(compilation) is maximal. If there is more than one such compilation return the one which is lexicographically earliest.

 

Definition

    
Class:MusicCompilation
Method:makeCompilation
Parameters:String[]
Returns:String[]
Method signature:String[] makeCompilation(String[] artists)
(be sure your method is public)
    
 

Constraints

-artists will contain between 0 and 50 elements inclusive.
-Each element in artists will be formatted as "<artist name> <number of hits>".
-<artist name> will contain between 1 and 10 letters ('a'-'z' and 'A'-'Z'), inclusive.
-<artist name> is case-sensitive and may not appear more than once in artists.
-<number of hits> will be an integer with no leading zeroes between 1 and 800 inclusive.
-The sum of all <number of hits> will be between 0 and 800 inclusive.
 

Examples

0)
    
{"Shakira 1","Jamiroquai 3","Gorillaz 2"}
Returns: {"Gorillaz", "Jamiroquai", "Jamiroquai", "Shakira", "Gorillaz", "Jamiroquai" }
Songs 1, 2 and 3 have distances 4, 1 and 3 respectively. Songs 4, 5 and 6 have distances of 0 because they are not followed by songs from the same artist. Hence, the distance of the compilation is 4 + 1 + 3 = 8. Although there are other compilations with the same distance, this is the lexicographically earliest.
1)
    
{"Radiohead 2","Spiderbait 3","LimpBizkit 4"}
Returns: 
{"LimpBizkit",
"Radiohead",
"Spiderbait",
"LimpBizkit",
"LimpBizkit",
"Spiderbait",
"LimpBizkit",
"Radiohead",
"Spiderbait" }
2)
    
{"Beatles 2","ABBA 1"}
Returns: {"Beatles", "ABBA", "Beatles" }
Call me old-fashioned, but I love these two bands!

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ChatExit

Greedy



Used in:

SRM 249

Used as:

Division I Level Two

Writer:

AdminBrett

Testers:

PabloGilberto , lbackstrom

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4614

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=7224&pm=4614

Problem Statement

    A group of people have participated in an online chat session. Element i (0-based) of numSeen contains the number of lines of chat seen by person i before leaving (everyone arrives at the same time). More precisely, integer j in element i of numSeen is the exact number of lines written by person j that are seen by person i before leaving. Integer i of element i will always be 0, and should be ignored. You will return a int[] containing the order in which each person left. If multiple orders are possible, return the one that occurs first lexicographically. If none are possible, return an empty int[].
 

Definition

    
Class:ChatExit
Method:leaveOrder
Parameters:String[]
Returns:int[]
Method signature:int[] leaveOrder(String[] numSeen)
(be sure your method is public)
    
 

Notes

-Order A comes lexicographically before order B if A has a lower value than B in the first position that they disagree.
 

Constraints

-numSeen will contain between 2 and 25 elements inclusive.
-Each element of numSeen will contain between 3 and 50 characters inclusive.
-Each element of numSeen will be a single space delimited list of integers. Each integer will be between 0 and 100 inclusive, and will have no extra leading zeros.
-Each element of numSeen will contain exactly k integers, where k is the number of elements in numSeen.
-Integer i in element i of numSeen will always be 0.
 

Examples

0)
    
{
"0 1 1",
"2 0 0",
"3 1 0"
}
Returns: {1, 0, 2 }
A possible sequence of events is:

Person 0 writes a line.

Person 1 writes a line.

Person 0 writes a line.

Person 1 leaves.

Person 2 writes a line.

Person 0 writes a line.

Person 0 leaves.

Person 2 leaves.

1)
    
{
"0 1 1",
"4 0 0",
"3 1 0"
}
Returns: { }
No order is possible here due to the following requirements:
  1. Person 1 must see 4 lines from person 0, but person 2 must only see 3 lines from person 0.
  2. Person 0 must see 1 line from person 2, but person 1 must not see any.
The first item above forces person 1 to leave after person 2. The second item forces person 1 to leave before person 2.
2)
    
{
"0 100 100 100 100 100",
"100 0 100 100 100 100",
"100 100 0 100 100 100",
"100 100 100 0 100 100",
"100 100 100 100 0 100",
"100 100 100 100 100 0"
}
Returns: {0, 1, 2, 3, 4, 5 }
Everyone says exactly 100 lines. Any leaving order is possible. The lexicographically first order is returned.
3)
    
{
"0 1 0 0",
"1 0 0 0",
"0 0 0 0",
"0 0 0 0"
}
Returns: {2, 3, 0, 1 }
4)
    
{
"0 0 0 0 0",
"0 0 0 0 0",
"0 0 0 0 0",
"0 0 0 0 0",
"0 0 0 0 0"
}
Returns: {0, 1, 2, 3, 4 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SandTimers

Graph Theory



Used in:

SRM 245

Used as:

Division I Level Three

Writer:

vorthys

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4587

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=7220&pm=4587

Problem Statement

    

Sigh... If only the king could make up his mind. First he wanted rounds in the Royal Wrestling Tournament to last for 2 minutes, then he changed his mind to 3 minutes. He wanted periods in the Royal Hockey Tournament to last for 20 minutes, then he decided on 15. Your job as the Royal Time Keeper would be much easier if he would buy you a modern stopwatch, but he insists that you use the Royal Sand Timers, which have been in his family since the 14th century. You're worried that someday he is going to ask you to measure a time interval that simply can't be measured with the timers you have available.

Given a int[] timers of the times that each of your timers can measure, you want to determine which integral intervals between 1 minute and maxInterval minutes (inclusive) cannot be measured. You always begin with all the sand in the bottom of your timers. You turn over some or all of your timers and the sand begins to fall. Whenever the sand runs out of a timer, you can again turn over some timers. You yell "Start" when you turn over some timer and "Stop" when the sand runs out of some timer. The time between the yells is the interval you are measuring. Because the king's patience is limited, you must yell "Stop" no later than maxTime minutes after turning over the first sand timer.

For example, if you had a 5-minute timer and a 7-minute timer, you could easily measure intervals of 5, 7, and 10 minutes. With a little more trouble you can measure intervals of 2, 3, 4, and 9 minutes. To measure 4 minutes, you start by flipping over both timers. When the 5-minute timer runs out, you flip it over and yell "Start", leaving the 7-minute timer running. When the 7-minute timer runs out two minutes later, you again flip over the 5-minute timer, which has been running for two minutes. The 5-minute timer runs out two minutes later, and you yell "Stop". However, no matter how you try, you cannot find a way to measure 1, 6, or 8 minutes, assuming the king's patience is limited to 10 minutes.

You will return a int[] of the intervals you cannot measure, arranged in increasing order. Note that, after years of training, you are able to turn over a sand timer instantaneously. However, tradition forbids you to ever lay a sand timer on its side.

 

Definition

    
Class:SandTimers
Method:badIntervals
Parameters:int[], int, int
Returns:int[]
Method signature:int[] badIntervals(int[] timers, int maxInterval, int maxTime)
(be sure your method is public)
    
 

Constraints

-timers contains between 1 and 3 elements, inclusive.
-Each element of timers is between 1 and 20, inclusive.
-maxInterval is between 1 and 360, inclusive.
-maxTime is between 1 and 360, inclusive.
-maxInterval is no greater than maxTime.
 

Examples

0)
    
{ 5, 7 }
10
10
Returns: {1, 6, 8 }
The example above.
1)
    
{ 2, 10, 20 }
30
40
Returns: {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29 }
All your timers are even, so you can't measure an odd number of minutes.
2)
    
{ 2, 5, 9 }
360
360
Returns: { }
You can measure all possible intervals.
3)
    
{ 4 }
23
47
Returns: {1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17, 18, 19, 21, 22, 23 }
4)
    
{ 20, 13 }
30
30
Returns: 
{1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 28, 29, 30 }
5)
    
{ 20, 17, 13 }
25
30
Returns: {18, 19 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

OddDigitable

Graph Theory, Math



Used in:

SRM 255

Used as:

Division I Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4527

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=7228&pm=4527

Problem Statement

    

An odd-digitable number is a positive integer which consists of only odd digits. For example, 1, 7, 15, 91 and 73353 are odd-digitable numbers, but 2, 70, 94 and 72653 are not odd-digitable.

You will be given integers N and M. Your method should return the smallest odd-digitable number that equals M modulo N. Your method should return "-1"(quotes for clarity only) if there are no such odd-digitable numbers.

 

Definition

    
Class:OddDigitable
Method:findMultiple
Parameters:int, int
Returns:String
Method signature:String findMultiple(int N, int M)
(be sure your method is public)
    
 

Constraints

-N will be between 2 and 100000, inclusive.
-M will be between 0 and N-1, inclusive.
 

Examples

0)
    
10
7
Returns: "7"
1)
    
22
12
Returns: "-1"
2)
    
29
0
Returns: "319"
3)
    
5934
2735
Returns: "791957"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AirTravel

Advanced Math, Geometry, Graph Theory, Search



Used in:

SRM 241

Used as:

Division II Level Three

Writer:

timmac

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4501

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=7216&pm=4501

Problem Statement

    

You are working for a shipping company, TopShipper, that specializes in shipping products by air. Your cargo jets transport items between a set of airports. From each airport, you can travel directly to some subset of the other airports. (Some airports may be too far, or may not have a safe passageway.) The ability to travel from one airport to another does not guarantee the ability to travel directly in the opposite direction.

You are about to send out a cargo plane on a trip to pick up a large shipment of a certain product. Unfortunately, only one other airport has this product for pickup, and you aren't guaranteed that there is a safe, direct route to the other airport. You may have to travel through one or more other airports to get to your final destination. Nonetheless, you wish to ultimately end up at the airport that has your desired product, and which you can get to by travelling the shortest possible distance.

You are to return a double indicating the number of miles travelled by the cargo plane along the optimal route from the origin to the destination. If no such route exists, return -1.

Given two coordinates, (lat1, lon1) and (lat2, lon2), the shortest distance between them is across an arc known as a great circle. The arclength along a great circle, between two points on the earth can be calculated as:

radius * acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon1 - lon2))

For purposes of this problem, the radius of the earth is 4000 miles.

You are given the latitude and longitude coordinates of each airport in latitude and longitude. The i-th element of latitude corresponds to the i-th element of longitude. You are also given String[] canTravel. The i-th element of canTravel is a space-delimited list of the 0-based indices of the airports that can be reached from airport i. Finally, you are given origin and destination, the indices of the airports at which you start and end your trip.

 

Definition

    
Class:AirTravel
Method:shortestTrip
Parameters:int[], int[], String[], int, int
Returns:double
Method signature:double shortestTrip(int[] latitude, int[] longitude, String[] canTravel, int origin, int destination)
(be sure your method is public)
    
 

Constraints

-latitude, longitude, and canTravel will contain between 1 and 20 elements, inclusive.
-latitude, longitude, and canTravel will each contain the same number of elements.
-Each element of latitude will be between -89 and 89, inclusive.
-Each element of longitude will be between -179 and 179, inclusive.
-Each element of canTravel will be a space-delimited list of integers, with no leading zeroes.
-Each integer represented in each element of canTravel will be between 0 and n - 1, where n is the number of elements in latitude.
-origin and destination will be between 0 and n - 1, inclusive, where n is the number of elements in latitude.
-No two airports will reside at the same latitude and longitude.
 

Examples

0)
    
{0, 0, 70}
{90, 0, 45}
{"2", "0 2", "0 1"}
0
1
Returns: 10612.237799994255

Here, we are looking to travel from airport 0 to airport 1.

Using the given formula, we calculate that the distance from 0 to 1 is 6283, from 0 to 2 is 5306, and from 1 to 2 is 5306.

A direct route from airport 0 to 1 would be fastest, if such a route were allowed. Since it is not, we have to travel through airport 2.

1)
    
{0, 0, 70}
{90, 0, 45}
{"1 2", "0 2", "0 1"}
0
1
Returns: 6283.185307179586
Here, we have the same three airports, and there is a safe route between any two. Thus, we take the direct route, which is quickest.
2)
    
{0, 30, 60}
{25, -130, 78}
{"1 2", "0 2", "1 2"}
0
0
Returns: 0.0
We are free to travel as we wish, but since our destination is the same as our point of origin, we don't have much travel to do.
3)
    
{0, 20, 55}
{-20, 85, 42}
{"1", "0", "0"}
0
2
Returns: -1.0
Notice here that we could go from airport 2 to airport 0, but not from 0 to 2. Given the available routes, there is no way we can get from airport 0 to airport 2.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PolyominoCut

Graph Theory, Recursion, Simple Math



Used in:

SRM 242

Used as:

Division I Level Three

Writer:

gepa

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4489

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=7217&pm=4489

Problem Statement

    

You are given a rectangular board consisting of width times height small squares. Return the number of different ways there are to cut a k-polyomino out of this board, so that the remaining part remains connected.

A k-polyomino is a connected set of k squares. The figure below shows as an example all possible pentominoes (5-polyominoes) ignoring any translations, rotations or reflections.

Connected means side-connected here (both in the polyomino definition and in the requirement for the remaining part of the board) - i.e., you must be able to go from any square to any other by only going through squares and square-sides but not square-corners.

For two ways of cutting a polyomino out of the grid to be different and be counted separately it suffices if at least one grid square is included in the first polyomino but not in the other.

The example below shows some polyomino cuts for k=7. The two on the left (red) are not counted, since they leave the remaining grid disconnected, while the one on the right (green) is counted.

 

Definition

    
Class:PolyominoCut
Method:count
Parameters:int, int, int
Returns:int
Method signature:int count(int k, int width, int height)
(be sure your method is public)
    
 

Constraints

-k will be between 1 and 8, inclusive.
-width and height will be between k+1 and 800, inclusive.
 

Examples

0)
    
1
10
20
Returns: 200
There is only one 1-polyomino (called monomino), and this can be cut out anywhere on the grid.
1)
    
3
10
10
Returns: 480

There are in total 484 ways to cut a triomino (3-polyomino) out of a 10x10 square, but 4 of them leave a square in the corner not connected (see figure below), so only 480 satisfy the problem requirements.

2)
    
8
800
800
Returns: 1704053350
The worst case fits in an int.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CalcButton

Brute Force



Used in:

SRM 246

Used as:

Division I Level Two , Division II Level Three

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4472

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=7221&pm=4472

Problem Statement

    

You are developing a new software calculator. You decided to add a new feature - the three-digit button. Clicking on this button will add three digits into the edit field. This feature is for fast typing of common digit combinations. The problem is to figure out which digits should be placed on this button. You have prepared some statistical data - a long sequence of digits. You have decided that the button will be chosen to minimize the quantity of clicking required for typing this sequence.

You will be given a String[] sequence. The data is divided into several rows only for convenience. You can assume that this is a solid array (i.e. the first character in the i-th row is directly after the last character in the (i-1)-th row). You should return a three-character String containing the digits on the button. If there are several solutions you should return the one which appears first lexicographically.

 

Definition

    
Class:CalcButton
Method:getDigits
Parameters:String[]
Returns:String
Method signature:String getDigits(String[] sequence)
(be sure your method is public)
    
 

Constraints

-sequence will have between 1 and 50 elements, inclusive.
-Each element of sequence will contain between 1 and 50 characters, inclusive.
-Each element of sequence will contain only digits ('0'-'9').
 

Examples

0)
    
{"100002000"}
Returns: "000"
We can type the sequence in 5 clicks (the extra button is used twice)
1)
    
{"777777777"}
Returns: "777"
We can type the entire sequence in 3 clicks
2)
    
{"6503","210"}
Returns: "032"
A sequence can be divided into several rows.
3)
    
{"0993034","6","4137","45959935","25939","93993","0","9358333"}
Returns: "993"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

NumberSplit

Dynamic Programming, Graph Theory, Simple Math



Used in:

SRM 242

Used as:

Division II Level Three

Writer:

gepa

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4451

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=7217&pm=4451

Problem Statement

    

We start with an integer and create a sequence of successors using the following procedure: First split the decimal representation of the given number into several (at least two) parts, and multiply the parts to get a possible successor. With the selected successor, we repeat this procedure to get a third number, and so on, until we reach a single-digit number.

For example, let's say we start with the number 234. The possible successors are:

  • 23 * 4 = 92,
  • 2 * 34 = 68 and
  • 2 * 3 * 4 = 24.
If we select 68 as the successor, we then generate 6 * 8 = 48 (the only possibility), from this we generate 4 * 8 = 32 and finally 3 * 2 = 6. With this selection, we have generated a sequence of 5 integers (234, 68, 48, 32, 6).

Given the starting number, start, return the length of the longest sequence that can be generated with this procedure. In the example, the given sequence would be the longest one since the other selections in the first step would give the sequences: (234, 92, 18, 8) and (234, 24, 8), which are both shorter than (234, 68, 48, 32, 6).

 

Definition

    
Class:NumberSplit
Method:longestSequence
Parameters:int
Returns:int
Method signature:int longestSequence(int start)
(be sure your method is public)
    
 

Notes

-There can not exist an infinite sequence.
-Although we use no leading zeros in the decimal representation of the number we start with, the parts we get by splitting the number may have leading zeros (e.g. from 3021 we can get 3 * 021 = 63).
 

Constraints

-start is between 1 and 100000, inclusive.
 

Examples

0)
    
6
Returns: 1
A single-digit number is already the last number.
1)
    
97
Returns: 4
For two-digit numbers, there is always only one possible sequence. Here: 97 -> 63 -> 18 -> 8 (4 numbers).
2)
    
234
Returns: 5
The example from the problem statement.
3)
    
876
Returns: 7
Here, it is optimal to make a three way split in the first step - i.e. use 8*7*6=336 as the first successor. Although a two way split would lead to a larger number (87*6=522 or 8*76=608), both these choices would lead in the end to a shorter sequence. The optimal sequence is: 876, 8*7*6=336, 33*6=198, 19*8=152, 1*52=52, 5*2=10, 1*0=0.
4)
    
99999
Returns: 29

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SnakeCount

Recursion



Used in:

SRM 284

Used as:

Division II Level Three

Writer:

dgoodman

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4435

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8081&pm=4435

Problem Statement

    We are using aerial photography to estimate the number of snakes in a region. We have a rectangular image of pixels with values 0 or 1, and we want to count the number of snakes in the image. The 0's are background, and the 1's are snake-colored. Because of the attributes of this type of snake (not gregarious and not likely to curl up tightly), we have adopted the following rules for identifying a snake:
  • A snake is never adjacent to a snake-colored pixel that is not part of itself, not even diagonally.
  • There is a sequence of orthogonally adjacent pixels that traces out the entire snake from its head to its tail.
  • Two pixels of a snake cannot be orthogonally adjacent unless they are connected in the snake (i.e., are neighbors in the sequence that traces out the snake).
  • A snake occupies between 3 and 20 pixels, inclusive.
As an example, consider the following picture. There are several ways to trace an orthogonal connection from a head to a tail, but it is NOT a snake since whichever way you trace out the snake, there are pixels that are orthogonally adjacent to each other but which are not neighbors in the sequence that traced out the snake.

    11110
    01110

Create a class SnakeCount that contains a method number that is given a String[] image and that returns the number of snakes in the image.

 

Definition

    
Class:SnakeCount
Method:number
Parameters:String[]
Returns:int
Method signature:int number(String[] image)
(be sure your method is public)
    
 

Notes

-A pixel is "orthogonally" adjacent to another if it is directly above, below, left or right of the other pixel.
 

Constraints

-image will contain between 1 and 50 elements, inclusive.
-Each element of image will contain exactly n characters, where n is between 1 and 50, inclusive.
-Each character in each element of image will be '0' (zero) or '1' (one).
 

Examples

0)
    
{"11111111",
 "00000010",
 "11100000",
 "00010001",
 "10110011"}
Returns: 1
The possible snake at the top does not have a head to tail connection that includes all its pixels. The 2 possible snakes of length 3 in the middle of the image are eliminated because each is adjacent to a snake-colored pixel diagonally. The possible snake in the lower left corner is too short. There is a snake in the lower right corner.
1)
    
{"110111",
 "110101",
 "000110"}
Returns: 1
The four pixels in the upper left do not make a snake -- the head of a snake cannot be orthogonally adjacent to its tail. The 7 snake-colored pixels in the right 3 columns do make a legitimate snake.
2)
    
{"111","101","111"}
Returns: 0
This is not a snake since the head cannot be orthogonally adjacent to the tail.
3)
    
{
"11111111111111111111111111111111111111111111111111",
"00000000000000000000000000000000000000000000000001",
"11111111111111111111111111111111111111111111111111"
}
Returns: 0
A snake can not occupy more than 20 pixels.
4)
    
{
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"00000000000000000000000000000000000000000000000000",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"00000000000000000000000000000000000000000000000000",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"00000000000000000000000000000000000000000000000000",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"00000000000000000000000000000000000000000000000000",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"00000000000000000000000000000000000000000000000000",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"00000000000000000000000000000000000000000000000000",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"00000000000000000000000000000000000000000000000000",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"00000000000000000000000000000000000000000000000000",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"00000000000000000000000000000000000000000000000000",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"00000000000000000000000000000000000000000000000000",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"00000000000000000000000000000000000000000000000000",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"10101010101010101010101010101010101010101010101010",
"00000000000000000000000000000000000000000000000000",
"11011011011011011011011011011011011011011011011011",
"10010010010010010010010010010010010010010010010001"
}
Returns: 317
A lot of snakes.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LongBlob

Graph Theory, Search



Used in:

SRM 292

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4434

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9813&pm=4434

Problem Statement

    A satellite image consists of a rectangular grid of 1x1 squares, each having a value of 0 or 1. We want to identify the longest "blob", where a blob is a collection of 0's that are connected orthogonally. The length of a blob is defined to be the maximum Euclidean distance between the centers of any two 0's in the blob. For example, in the following image
       0010
       1001
       0011
       0111   
there are 2 blobs. The length of the big blob is sqrt(1+9), the distance between the 0 in the lower left corner and the one in row 0, column 1. The length of the tiny blob is 0.

The difficulty is that the image may contain some noise in the form of 1's that should be 0's. We do not want to underestimate the length of the longest blob. So we will consider all different ways of choosing up to 4 different 1's and replacing them with 0's. Among all these altered images we want the length of the longest blob.

Create a class LongBlob that contains a method maxLength that is given a String[] image and that return the length of the longest blob when up to 4 of the 1's in image are regarded as noise.

 

Definition

    
Class:LongBlob
Method:maxLength
Parameters:String[]
Returns:double
Method signature:double maxLength(String[] image)
(be sure your method is public)
    
 

Notes

-A return value with either an absolute or relative error of less than 1.0E-9 is considered correct.
 

Constraints

-image will contain between 1 and 25 elements inclusive.
-Each element of image will contain exactly n characters, where n is between 1 and 25 inclusive.
-Each element of image will contain only the characters '0' (zero) and '1' (one).
 

Examples

0)
    
{"0010",
 "1001",
 "0011",
 "0111"}
Returns: 4.242640687119285
This is the example given above but now by replacing 4 1's with 0's we can get a blob that includes diagonally opposite corners. The distance between two opposite corners is sqrt(9 + 9).
1)
    
{"101010101"}
Returns: 7.0
Replace the first 4 1's with 0's. Then there is one long blob, whose length is the distance between the first 0 (that used to be a 1) and the last 0.
2)
    
{"1010101010101010101010101",
 "0101010101010101010101010",
 "1010101010101010101010101",
 "0101010101010101010101010",
 "1010101010101010101010101",
 "0101010101010101010101010",
 "1010101010101010101010101",
 "0101010101010101010101010",
 "1010101010101010101010101",
 "0101010101010101010101010",
 "1010101010101010101010101",
 "0101010101010101010101010",
 "1010101010101010101010101",
 "0101010101010101010101010",
 "1010101010101010101010101",
 "0101010101010101010101010",
 "1010101010101010101010101",
 "0101010101010101010101010",
 "1010101010101010101010101",
 "0101010101010101010101010",
 "1010101010101010101010101",
 "0101010101010101010101010",
 "1010101010101010101010101",
 "0101010101010101010101010",
 "1010101010101010101010101"}
Returns: 8.0
3)
    
{"01011",
 "11100",
 "01110",
 "11111",
 "01011",
 "11111"}
Returns: 5.656854249492381

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CircleCount

Graph Theory, Sorting



Used in:

TCCC07 Round 1C

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

PabloGilberto , Olexiy , ivan_metelsky , andrewzta

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4432

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10899&pm=4432

Problem Statement

    We have a circular track on which a number of loaded cars are located. Each car has its own specified unloading position along the track. The cars can be moved in either direction along the track, but cannot pass each other.

We want to make a worklist, specifying the order in which the cars should be moved. The order of cars in the worklist must allow each car to be moved just once all the way to its unloading position. How many different orders will allow this?

The cars are each named with a lowercase letter, and their destinations with the same letter but in uppercase. The positions of the cars and of their destinations are given by a sequence of letters that is regarded as circular by wrapping around the ends. So, for example, "BACacb" describes a situation in which going clockwise around the track we encounter B, A, C, a, c, b, and then return back to B. Here there are 3 different orders in which the cars can be moved to their destinations: a then c then b, a then b then c, or b then a then c.

Given the original positions of the cars and destinations in a String circle, return the number of different orders in which the cars can be moved. If there are more than 2,000,000,000 orders return -1. If no order is possible, your method should return 0.

 

Definition

    
Class:CircleCount
Method:countOrder
Parameters:String
Returns:int
Method signature:int countOrder(String circle)
(be sure your method is public)
    
 

Constraints

-circle will contain between 2 and 50 characters, inclusive.
-Each character will be a letter ('a'-'z', 'A'-'Z').
-No character will appear more than once in circle.
-If a letter appears in circle, it will appear both in uppercase and in lowercase.
 

Examples

0)
    
"BACacb"
Returns: 3
This is the example given above.
1)
    
"ABCacb"
Returns: 0
We cannot move c first. If we move a first, then we can never move b to B, but if we move b first we can never move a to A.
2)
    
"xX"
Returns: 1
We must move car x. We could move it to its destination either in a clockwise or a counterclockwise direction but there is only one order for choosing the cars to move.
3)
    
"ABCabc"
Returns: 2
The possibilities are 1) a then b then c, or 2) c then b then a (moving the cars in the other direction).
4)
    
"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPp"
Returns: -1
These 16 cars can be move in any order, so there are 16! orders which is greater than 2,000,000,000

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AcademicJournal

Graph Theory, Sorting, String Parsing



Used in:

SRM 235

Used as:

Division II Level Three

Writer:

the_one_smiley

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4020

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6534&pm=4020

Problem Statement

    

In any field of research, there are many journals to which one can submit an article for publication. One criterion that is commonly used to choose between journals is the impact factor, a measure of the importance of a journal and the papers that are published there. The impact factor of a journal is defined as the average number of citations each paper in that journal receives from papers in other journals. Citations from papers in the same journal are not counted in order to prevent its editors from inflating their impact factor by preferentially accepting papers that cite other papers in their journal. Although impact factors are not a fair way to judge the quality of research, they do provide a quantitative method for comparing journals to each other.

Write a class AcademicJournal with a method rankByImpact that takes a String[] papers, a collection of published papers from which to calculate impact factors, and returns a String[] with the journal names sorted in decreasing order by impact factor. Each element of papers contains the information for a single paper, and is formatted with the name of the paper's journal (consisting of only uppercase English characters and spaces), followed by a period, followed by zero or more integers specifying the zero-based indices of the papers it cites. The citation indices contain no extra leading zeroes, and are separated from each other and from the period character by single spaces. If there is a tie in the impact factors, the journal with more papers comes first in the return value. If there is still a tie, the journal with the lexicographically earlier name comes first.

 

Definition

    
Class:AcademicJournal
Method:rankByImpact
Parameters:String[]
Returns:String[]
Method signature:String[] rankByImpact(String[] papers)
(be sure your method is public)
    
 

Notes

-Although it is not supposed to happen, it is possible for two papers to reference each other due to delays in the editing and publishing process.
-A sloppy author or editor of a paper might accidentally include multiple citations to another paper. In your calculation of the impact factors, count citations from one paper to another only once.
 

Constraints

-papers will contain between 1 and 50 elements, inclusive.
-Each element of papers will contain between 2 and 50 characters, inclusive.
-Each element of papers will be formatted as described in the problem statement.
-Each index will be between 0 and the number of papers - 1, inclusive.
-A paper will not contain a reference to itself.
 

Examples

0)
    
{"A.", "B. 0", "C. 1 0 3", "C. 2"}
Returns: {"A", "B", "C" }
The one paper in journal A is cited two times, so A's impact factor is 2/1. The one paper in journal B is cited once, so B's impact factor is 1/1. The two papers in journal C only receive citations from each other. Since citations from a paper in the same journal do not count, C's impact factor is 0/2.
1)
    
{"RESPECTED JOURNAL.", "MEDIOCRE JOURNAL. 0", "LOUSY JOURNAL. 0 1",
"RESPECTED JOURNAL.", "MEDIOCRE JOURNAL. 3", "LOUSY JOURNAL. 4 3 3 4",
"RESPECTED SPECIFIC JOURNAL.", "MEDIOCRE SPECIFIC JOURNAL. 6", "LOUSY SPECIFIC JOURNAL. 6 7"}
Returns: 
{"RESPECTED JOURNAL",
"RESPECTED SPECIFIC JOURNAL",
"MEDIOCRE JOURNAL",
"MEDIOCRE SPECIFIC JOURNAL",
"LOUSY JOURNAL",
"LOUSY SPECIFIC JOURNAL" }
There is an impact factor tie between the SPECIFIC and non-specific versions of each tier of journal. Since the non-specific ones have more papers, they win the tiebreaker.
2)
    
{"NO CITATIONS.", "COMPLETELY ORIGINAL."}
Returns: {"COMPLETELY ORIGINAL", "NO CITATIONS" }
If there is a tie in impact factor and number of papers, the journal with the lexicographically earlier name comes first.
3)
    
{"CONTEMPORARY PHYSICS. 5 4 6 8 7 1 9",
"EUROPHYSICS LETTERS. 9",
"J PHYS CHEM REF D. 5 4 6 8 7 1 9",
"J PHYS SOC JAPAN. 5 4 6 8 7 1 9",
"PHYSICAL REVIEW LETTERS. 5 6 8 7 1 9",
"PHYSICS LETTERS B. 6 8 7 1 9",
"PHYSICS REPORTS. 8 7 1 9",
"PHYSICS TODAY. 1 9",
"REP PROGRESS PHYSICS. 7 1 9",
"REV MODERN PHYSICS."}
Returns: 
{"REV MODERN PHYSICS",
"EUROPHYSICS LETTERS",
"PHYSICS TODAY",
"REP PROGRESS PHYSICS",
"PHYSICS REPORTS",
"PHYSICS LETTERS B",
"PHYSICAL REVIEW LETTERS",
"CONTEMPORARY PHYSICS",
"J PHYS CHEM REF D",
"J PHYS SOC JAPAN" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BasicSorting

Graph Theory, Recursion, Search, Sorting



Used in:

TCCC05 Finals

Used as:

Division I Level Two

Writer:

lars2520

Testers:

PabloGilberto , lbackstrom , Yarin , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=4005

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6554&pm=4005

Problem Statement

    You have a few very large files and they need to be sorted according to a total order that is defined for them. The only information you can use to sort them is the relative orders of pairs of files. Unfortunately, finding the relative order of a pair takes N*M minutes where N and M are the sizes of the two files being compared. Given the sizes of the files being sorted, your task is to find a comparison plan that guarantees you will find the correct order in the minimal amount of time. You should return that minimum.
 

Definition

    
Class:BasicSorting
Method:minSortTime
Parameters:int[]
Returns:int
Method signature:int minSortTime(int[] sizes)
(be sure your method is public)
    
 

Notes

-No two files are 'equal' -- one of them always belongs strictly after the other in the ordering.
 

Constraints

-sizes will contain between 2 and 6 elements, inclusive.
-Each element of sizes will be between 1 and 100, inclusive.
 

Examples

0)
    
{1,2,3}
Returns: 11
With 3 files, you must compare all 3 pairs of files to figure out the order. The total time is thus 1*2 + 1*3 + 2*3 = 11 minutes.
1)
    
{1,1,1,1}
Returns: 5
One way to do this is to find the order on three of the files, which takes 3 minutes. Then, compare the fourth file to the middle one of those three files. Finally, if the fourth file comes after the middle file, compare it to the last file, while if it comes before the fourth file, compare it to the first file.
2)
    
{15,74,61,34,21}
Returns: 12477

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RunLengthPlus

Dynamic Programming, Encryption/Compression, String Manipulation



Used in:

TCCC05 Wildcard

Used as:

Division I Level One

Writer:

lars2520

Testers:

PabloGilberto , Yarin , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3961

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6553&pm=3961

Problem Statement

    One type of compression is run length encoding. In this case, a character may be preceded by an integer N, which indicates that the character should be repeated N times. For example, the String "3ABBC10D" would be decompressed as "AAABBCDDDDDDDDDD". A character that is not preceded by an integer is repeated just once. We are going to enrich this slightly be allowing a sequence of characters to be preceded by an integer N, indicating that the sequence should be repeated N times. In this case, the sequence of characters should be surrounded by parentheses. Additionally, you may nest the compressed sequences. Thus, the compressed sequence "X2(2A3(BC))X" would be decompressed as "XAABCBCBCAABCBCBCX". You will be given a String of uppercase letters and are to compress it in such a way that the result has as few characters as possible. If there are multiple ways to do this, choose the one that comes first lexicographically (using standard ASCII ordering).
 

Definition

    
Class:RunLengthPlus
Method:compress
Parameters:String
Returns:String
Method signature:String compress(String s)
(be sure your method is public)
    
 

Constraints

-s will contain between 1 and 50 uppercase letters, inclusive.
 

Examples

0)
    
"AAABBCDDDDDDDDDD"
Returns: "3A2BC10D"
1)
    
"XAABCBCBCAABCBCBCX"
Returns: "X2(2A3(BC))X"
2)
    
"ABCBACBABCBABCABACACBCBABACBCBBABACBACBCACBBAC"
Returns: "ABCBA2(CBAB)CABACACBCBABACBC2BA2(BAC)BCAC2BAC"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Indivisible

Greedy



Used in:

TCCC05 Wildcard

Used as:

Division I Level Two

Writer:

vorthys

Testers:

PabloGilberto , lbackstrom , Yarin

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3957

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6553&pm=3957

Problem Statement

    

Given a positive integer n, you are to find the largest subset S of {1,...,n} such that no member of S is divisible by another member of S. If there is more than one subset of the maximum size, choose the lexicographically earliest such subset. A subset S is lexicographically earlier than a subset T if the smallest element that is a member of one of the subsets, but not both, is a member of S. Return the subset S as a int[] in increasing order.

 

Definition

    
Class:Indivisible
Method:largestSubset
Parameters:int
Returns:int[]
Method signature:int[] largestSubset(int n)
(be sure your method is public)
    
 

Constraints

-n is between 1 and 1000, inclusive.
 

Examples

0)
    
10
Returns: {4, 5, 6, 7, 9}
There are several possible subsets of size 5, such as { 4,6,7,9,10 }, but { 4,5,6,7,9 } is the lexicographically earliest.
1)
    
1
Returns: {1}
2)
    
5
Returns: {2, 3, 5}
3)
    
24
Returns: {4, 6, 9, 10, 11, 13, 14, 15, 17, 19, 21, 23}

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Shouting

Brute Force, Graph Theory



Used in:

TCCC05 Semi 2

Used as:

Division I Level One

Writer:

dgoodman

Testers:

PabloGilberto , lbackstrom , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3950

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6551&pm=3950

Problem Statement

    Two people are within "shouting distance" if one can hear the other one shout. We have a group of identical people located across the countryside. We want to know how small the shouting distance can be and still allow a message to originate with anyone and be heard by everyone else by a sequence of shouts.

The locations of the people are given by int[]'s x and y, with the location of the i-th person given by the i-th element of x and the i-th element of y. Create a class Shouting that contains a method shout that is given x and y and that returns the smallest shouting distance that will allow complete communication.

 

Definition

    
Class:Shouting
Method:shout
Parameters:int[], int[]
Returns:double
Method signature:double shout(int[] x, int[] y)
(be sure your method is public)
    
 

Notes

-The returned value must be accurate to within a relative or absolute value of 1E-9.
 

Constraints

-x and y will contain the same number of elements, between 1 and 50 inclusive.
-Each element of x and y will be between -10,000 and 10,000 inclusive.
 

Examples

0)
    
{-2000,-2000}
{3000,3000}
Returns: 0.0
These two people are standing in the same spot, so there is no need to shout.
1)
    
{3,3,3,3,3,3,3}
{2,3,4,3,9,8,1}
Returns: 4.0
These people are standing in a line, and the biggest gap is between (3,4) and (3,8) which can be bridged by a shout of length 4.
2)
    
{5,0,-5,0}
{0,5,0,-5}
Returns: 7.0710678118654755
These people are standing in a square. Shouting around the edges of the square is the best way to communicate, and each edge has a length of 5*sqrt(2)
3)
    
{17}
{1912}
Returns: 0.0

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AutoMarket

Dynamic Programming, Graph Theory, Sorting



Used in:

SRM 233

Used as:

Division II Level Three

Writer:

ValD

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3937

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6532&pm=3937

Problem Statement

    It is expected that the more expensive the automobile, the more features are included and the less often it breaks down. While expected, this is not always true. Given a set of automobile specs, find the largest subset where the condition is reversed.



Write a class AutoMarket that contains a method maxSet, which accepts a int[] cost, int [] features and int[] fixTimes and returns the size of the largest subset that can be ordered such that each succeeding automobile costs more, has less features and must be fixed more often. All conditions are strict. The ith element in cost, features and fixTimes represents the ith car, which costs cost[i] dollars, has features[i] features and must be fixed fixTimes[i] times per year.
 

Definition

    
Class:AutoMarket
Method:maxSet
Parameters:int[], int[], int[]
Returns:int
Method signature:int maxSet(int[] cost, int[] features, int[] fixTimes)
(be sure your method is public)
    
 

Constraints

-cost, features and fixTimes will each have between 1 and 50 elements, inclusive.
-cost, features and fixTimes will have the same number of elements.
-Each element of cost will be between 1 and 100000, inclusive.
-Each element of features and fixTimes will be between 1 and 100, inclusive.
 

Examples

0)
    
{10000, 14000, 8000, 12000}
{1, 2, 4, 3}
{17, 15, 8, 11}
Returns: 3
The largest set contains all elements except the first.
1)
    
{1,2,3,4,5}
{1,2,3,4,5}
{1,2,3,4,5}
Returns: 1
2)
    
{9000, 6000, 5000, 5000, 7000}
{1, 3, 4, 5, 2}
{10, 6, 6, 5, 9}
Returns: 4
3)
    
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}
{20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1}
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}
Returns: 20
4)
    
{1000, 1000, 1000, 1000, 2000}
{3,3,4,3,3}
{3,3,3,4,3}
Returns: 1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SmartWordToy

Graph Theory



Used in:

SRM 233

Used as:

Division I Level Two

Writer:

ValD

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3935

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6532&pm=3935

Problem Statement

    The toy company "I Can't Believe It Works!" has hired you to help develop educational toys. The current project is a word toy that displays four letters at all times. Below each letter are two buttons that cause the letter above to change to the previous or next letter in alphabetical order. So, with one click of a button the letter 'c' can be changed to a 'b' or a 'd'. The alphabet is circular, so for example an 'a' can become a 'z' or a 'b' with one click.



In order to test the toy, you would like to know if a word can be reached from some starting word, given one or more constraints. A constraint defines a set of forbidden words that can never be displayed by the toy. Each constraint is formatted like "X X X X", where each X is a string of lowercase letters. A word is defined by a constraint if the ith letter of the word is contained in the ith X of the contraint. For example, the constraint "lf a tc e" defines the words "late", "fate", "lace" and "face".



You will be given a String start, a String finish, and a String[] forbid. Calculate and return the minimum number of button presses required for the toy to show the word finish if the toy was originally showing the word start. Remember, the toy must never show a forbidden word. If it is impossible for the toy to ever show the desired word, return -1.
 

Definition

    
Class:SmartWordToy
Method:minPresses
Parameters:String, String, String[]
Returns:int
Method signature:int minPresses(String start, String finish, String[] forbid)
(be sure your method is public)
    
 

Constraints

-start and finish will contain exactly four characters.
-start and finish will contain only lowercase letters.
-forbid will contain between 0 and 50 elements, inclusive.
-Each element of forbid will contain between 1 and 50 characters.
-Each element of forbid will contain lowercase letters and exactly three spaces.
-Each element of forbid will not contain leading, trailing or double spaces.
-Each letter within a group of letters in each element of forbid will be distinct. Thus "aa a a a" is not allowed.
-start will not be a forbidden word.
 

Examples

0)
    
"aaaa"
"zzzz"
{"a a a z", "a a z a", "a z a a", "z a a a", "a z z z", "z a z z", "z z a z", "z z z a"}
Returns: 8
1)
    
"aaaa"
"bbbb"
{}
Returns: 4
Simply change each letter one by one to the following letter in the alphabet.
2)
    
"aaaa"
"mmnn"
{}
Returns: 50
Just as in the previous example, we have no forbidden words. Simply apply the correct number of button presses for each letter and you're there.
3)
    
"aaaa"
"zzzz"
{"bz a a a", "a bz a a", "a a bz a", "a a a bz"}
Returns: -1
Here is an example where it is impossible to go to any word from "aaaa".
4)
    
"aaaa"
"zzzz"
{"cdefghijklmnopqrstuvwxyz a a a", 
 "a cdefghijklmnopqrstuvwxyz a a", 
 "a a cdefghijklmnopqrstuvwxyz a", 
 "a a a cdefghijklmnopqrstuvwxyz"}
Returns: 6
5)
    
"aaaa"
"bbbb"
{"b b b b"}
Returns: -1
6)
    
"zzzz"
"aaaa"
{"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
 "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk"}
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Parking

Graph Theory



Used in:

SRM 236

Used as:

Division I Level Three

Writer:

Jan_Kuipers

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3530

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6535&pm=3530

Problem Statement

    In a parking lot there are a lot of cars and parking spots and all cars want to drive to a parking spot. Due to the traffic regulations cars may only drive parallel to the boundaries of the parking lot and only at the speed of one square per unit of time.



Usually all cars drive to the nearest available parking spot, but that might turn out badly for some cars. Consider for example the following car park
.C.....P.X...
XX.......X..P
XX.....C.....
(here 'C' stands for car, 'P' for parking spot, 'X' for wall and '.' for empty spot)



If the car on the bottom drives to its nearest parking spot, the upper left car must drive all the way to the right, taking 13 units of time. If, however, the car on the bottom drives to the parking spot on the right, it will take 6 units of time for both cars to find a parking spot.



Return the minimal amount of time it takes before every car can have a parking spot (assuming that the cars act socially like above). All cars start on an empty spot. Cars are small and any number of them can drive on the same square simultaneously. They can drive over empty spots and parking spots, but not through walls. Each car has to end on a separate parking spot.



If it is impossible for each car to drive to a parking place, return -1.
 

Definition

    
Class:Parking
Method:minTime
Parameters:String[]
Returns:int
Method signature:int minTime(String[] park)
(be sure your method is public)
    
 

Constraints

-park will contain between 1 and 50 elements, inclusive.
-All elements of park have equal length.
-Each element of park has length between 1 and 50, inclusive.
-Each character in park is either 'C', 'P', 'X' or '.'.
-There will be no more than 100 cars and 100 parking places in park.
 

Examples

0)
    
{"C.....P",
 "C.....P",
 "C.....P"}
Returns: 6
Every car just drives to the opposite parking spot.
1)
    
{"C.X.....",
 "..X..X..",
 "..X..X..",
 ".....X.P"}
Returns: 16
The slalom takes the car 16 units of time.
2)
    
{"XXXXXXXXXXX",
 "X......XPPX",
 "XC...P.XPPX",
 "X......X..X",
 "X....C....X",
 "XXXXXXXXXXX"}
Returns: 5
This would take 11 instead of 5 units of time if the car on the bottom drove to its nearest parking spot.
3)
    
{".C.",
 "...",
 "C.C",
 "X.X",
 "PPP"}
Returns: 4
While driving, the cars can be on the same empty spot or parking spot, but they have to finish on different parking spots.
4)
    
{"CCCCC",
 ".....",
 "PXPXP"}
Returns: -1
There are not enough parking spots for all the cars.
5)
    
{"..X..",
 "C.X.P",
 "..X.."}
Returns: -1
The car can't reach the parking spot.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SnowClearing

Graph Theory



Used in:

SRM 229

Used as:

Division II Level Three

Writer:

AdrianKuegel

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3521

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6518&pm=3521

Problem Statement

    Square City got a new snow plow. Unfortunately, it is impossible for the plow to do a 180 degree turn at an intersection, and due to traffic rules it is not allowed to drive backwards. Soon it was realized that some streets can't be reached by the new snow plow and it is your job to calculate how many.

You are given a map of the city, consisting of '|', '+', '-' and ' '. For example, a possible map may look like this:

+-+-+-+-+-+-+
| | | | | | |
+-+ +-+ +-+ +
|   |   |    
+-+-+-+-+-+-+
Each '+' stands for an intersection, whereas '-' or '|' denotes a single two-way street.

In addition to the map, you are given the row number (counted from the top) and column number (counted from the left) of the snow plow's garage (both indexed from 1), where the plow starts its snow clearing tours. Note that only the rows and columns containing intersections are counted. After the snow clearing, the plow must be able to get back to the garage. Therefore, a street forming a dead end is not reachable because at the end intersection, the only possible way back would be using the same street, and a 180 degree turn is not possible. The only exception to this is that the plow can turn in any direction at the garage, so it is not important in which direction the plow is initially facing. Determine the number of streets which can't be cleared by the snow plow because there is no way back to the garage. In the example above, if the garage is at (2,7), there are two streets which can't be cleared: the streets connecting (3,5) with (3,6) and (3,6) with (3,7).
 

Definition

    
Class:SnowClearing
Method:unreachable
Parameters:String[], int, int
Returns:int
Method signature:int unreachable(String[] citymap, int row, int column)
(be sure your method is public)
    
 

Notes

-If citymap contains n elements, and each element has length m, then there are (n+1)/2 * (m+1)/2 intersections.
 

Constraints

-citymap contains an odd number (between 3 and 49, inclusive) of elements.
-Each element of citymap contains the same number of characters.
-Every second element of citymap consists of an odd number (between 3 and 49, inclusive) of characters from the set {'|',' '}, where character '|' can only appear at even positions in the string (positions 0, 2, ...).
-All other elements of citymap consists of an odd number (between 3 and 49, inclusive) of characters from the set {'+','-',' '}, where character '+' appears at every even position in the string (position 0, 2, ...).
-row will be between 1 and (1 + number of elements in citymap)/2, inclusive.
-column will be between 1 and (1 + length of elements in citymap)/2, inclusive.
-There will always be a path between each pair of intersections using the available streets.
 

Examples

0)
    
{"+-+-+-+-+-+-+"
,"| | | | | | |"
,"+-+ +-+ +-+ +"
,"|   |   |    "
,"+-+-+-+-+-+-+"}
2
7
Returns: 2
This is the example from above. The snow plow starts at the middle intersection, on the far right of the city. Since the snow plow can turn at the garage, it can do several tours and clear all streets but the two streets connecting (3,5) to (3,6) and (3,6) to (3,7).
1)
    
{"+-+"
,"| |"
,"+ +"}
1
1
Returns: 3
In this example, the snow plow can't clear any street, since it would get stuck at (2,1) or (2,2).
2)
    
{"+-+-+"
,"| | |"
,"+-+ +"}
1
3
Returns: 1
Note that it is not important in which direction the snow plow is initally facing. Therefore the only street it can't clear is the street connecting (1,3) to (2,3).
3)
    
{"+-+-+"
,"|   |"
,"+-+-+"}
2
2
Returns: 0
Here the snow plow can clear every street.
4)
    
{"+ +-+ +-+-+ +-+-+ +-+-+-+-+-+-+-+-+-+-+ +-+-+-+ +"
,"| |   | |     |   |   |         |     | |     | |"
,"+ +-+-+-+ +-+-+-+ +-+ +-+-+-+-+ +-+-+-+ +-+ +-+-+"
,"| | |       |   | |   |   |   |   |     | |   |  "
,"+ +-+-+ +-+-+ +-+-+-+-+-+-+-+ +-+ +-+ +-+ +-+ +-+"
,"|     | | | | |   |             |     |   | |   |"
,"+-+-+ +-+-+-+ +-+ +-+ + +-+-+-+-+-+ +-+-+ +-+-+-+"
,"|       | |     |     |   |         |   | |     |"
,"+-+-+-+ +-+-+-+-+-+-+-+-+-+-+ +-+ +-+ +-+-+-+-+-+"
,"      |   | |     |   | |     | | |   | |       |"
,"+ +-+-+-+-+ + +-+ +-+ +-+ +-+-+ +-+-+-+-+-+ +-+-+"
,"| |   | |     |   |         |   | | |     |   | |"
,"+-+-+-+-+-+ +-+-+ +-+-+-+ +-+-+ +-+-+ +-+-+ +-+-+"
,"          |   |   |   |   | |                    "
,"+-+-+-+-+-+-+ +-+-+-+ + +-+-+ +-+ +-+-+-+ +-+-+ +"
,"|                     | |     |   |   | |   | | |"
,"+ +-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+ +-+-+-+ + +-+"
,"| |     |   | | |   | | | |       | |   | | | | |"
,"+-+-+-+ +-+-+-+-+ +-+ + +-+ +-+-+-+ +-+-+ +-+ +-+"
,"    | |   | | |   |               |   |          "
,"+-+ +-+-+-+-+-+ +-+ + +-+-+-+-+-+-+ + + +-+-+ +-+"
,"  | | |         | | | |   |   | | | | | | | | |  "
,"+-+-+ + +-+ +-+ +-+-+-+-+ + + + +-+-+ +-+-+-+-+-+"
,"    | | | | | | |         | | |       |     | |  "
,"+ +-+ + + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+"
,"| |   | |     | |   |   |   |   |   | |         |"
,"+-+-+ +-+-+-+-+ +-+ + +-+-+-+-+ +-+ +-+-+-+-+-+-+"
,"      | |   | | | |     |       | |         | |  "
,"+-+ + +-+-+-+-+ + +-+-+-+ +-+-+-+-+ +-+ +-+-+-+-+"
,"  | | | |   |   |     | |   |   | |   | | |   |  "
,"+-+-+-+-+-+-+ +-+-+-+-+-+-+ +-+ +-+ +-+ +-+-+ +-+"
,"|     | | |   |     |     |   | | |   |   | | | |"
,"+-+-+-+-+-+-+ + +-+-+-+-+-+ +-+-+-+-+ +-+ + +-+-+"
,"| | | | |   | | |   | |         |     | | | |   |"
,"+ +-+ +-+-+ + + +-+-+ + + +-+-+-+-+ +-+ +-+-+-+-+"
,"  | | |   |     | |     |         |   | |   | | |"
,"+ +-+ +-+-+-+ +-+-+-+-+ +-+-+-+ +-+-+-+ +-+-+ + +"
,"|     | |     |   |           |   | | |   | | |  "
,"+-+-+-+-+-+-+-+ +-+-+ +-+-+-+-+-+ +-+-+ +-+-+ +-+"
,"|         |     |       | |   |       | | | | |  "
,"+-+-+-+ +-+-+-+-+-+-+-+-+ +-+ +-+ +-+-+ +-+-+-+-+"
,"        |   |   | | | | | | | | | | | | | |     |"
,"+-+-+-+-+-+-+-+ +-+-+ +-+-+ +-+-+-+ +-+ + +-+-+ +"
,"      | | | |       | |     | |   |       |   | |"
,"+ +-+-+-+-+-+ +-+ +-+ +-+-+-+ +-+-+-+-+-+ + +-+-+"
,"| | |       | | | |       |     | | | |       | |"
,"+-+-+-+-+-+-+-+ + +-+-+-+ + +-+-+-+-+-+-+-+ +-+ +"
,"      |   |   | |   | |         |     | | | | | |"
,"+-+-+-+-+-+-+-+-+-+ +-+-+-+-+ +-+-+-+ + + +-+-+ +"}
10
12
Returns: 160

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Loopy

Graph Theory, Recursion, String Parsing



Used in:

SRM 228

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3517

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6517&pm=3517

Problem Statement

    We have a program segment and want to analyze the control flow through it. We have already replaced the actual code with simpler code that captures just the control logic. The code we want to analyze consists of a sequence of statements in which each statement is one of the following two types:
  • IF target1 ELSE target2
  • RETURN
Execution of an IF statement is followed by execution of one of its two targets. Each target is an integer referring to a zero-based position in the code sequence. The two targets may be identical. Execution of a RETURN statement ends the execution.

Execution of the program segment starts at the first statement (statement 0) and concludes when it reaches a RETURN statement. We call such a sequence an "execution path."

In order to optimize the code, we want to find the smallest loop in the program segment that can be executed. A loop is defined to be a set of statements such that

  1. Only one statement in the loop (the entry point) may be immediately preceded in an execution path by a statement that is not in the loop.
  2. If a loop contains statement 0, then statement 0 must be the entry point for that loop.
  3. If a statement S is in the loop, then there is an execution path that executes S and then, without executing any statement outside the loop, executes every statement (including S) in the loop at least once.
Create a class Loopy that contains a method minLoop that is given a String[] code containing the sequence of statements and that returns the smallest number of statements in code that form a loop. If code contains no loop, return 0.
 

Definition

    
Class:Loopy
Method:minLoop
Parameters:String[]
Returns:int
Method signature:int minLoop(String[] code)
(be sure your method is public)
    
 

Constraints

-code will contain between 1 and 50 elements inclusive.
-Each element of code will be one of the two forms above.
-Each RETURN statement has no spaces.
-Each IF statement has exactly 3 spaces.
-Each target1 and target2 will be an integer with no extraneous leading zeroes.
-Each target1 and target2 will be between 0 and n-1 inclusive, where n is the number of elements in code.
 

Examples

0)
    
{"RETURN", "IF 0 ELSE 1"}
Returns: 0
Execution immediately returns, so there is no loop.
1)
    
{"IF 1 ELSE 2","IF 1 ELSE 2","RETURN"}
Returns: 1
Statement 1 forms a loop.
2)
    
{"IF 1 ELSE 2","RETURN", "IF 3 ELSE 2", "IF 2 ELSE 3"}
Returns: 0
No execution path that includes either statement 2 or 3 can ever reach a RETURN statement. The only legal execution path is statement 0 followed by statement 1 so there is no loop.
3)
    
{"IF 1 ELSE 2","IF 3 ELSE 3","IF 4 ELSE 1",
 "IF 4 ELSE 5","RETURN","IF 0 ELSE 6",
 "IF 6 ELSE 6","IF 7 ELSE 2"}
Returns: 5
Statements 0, 1, 2, 3, and 5 form a loop whose entry point is statement 0. Note that no execution path contains statement 7, so statement 2 is never preceded by a non-loop statement.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Justify

Dynamic Programming



Used in:

TCCC05 Qual 4

Used as:

Division I Level Three

Writer:

lars2520

Testers:

PabloGilberto , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3504

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6526&pm=3504

Problem Statement

    When a paragraph is justified, the widths of the spaces on each line except the last are adjusted so that each line except the last has exactly the same width. This is done in such a way that each space within a line has the same width (spaces can have any width, not just integral ones). This can lead to some lines with undesirably wide spaces. For example, if each line is 20 characters long, and one line contains 10 characters and 1 space, while the next contains 15 characters and 3 spaces, the space in the first line will be far wider than the spaces in the next line.



Your task is to find a way to place the words in a paragrah so that the width of the widest space is as small as possible. You may assume that each letter has the same width, and that each space must be at least as wide as one letter. You will be given a String[], paragraph, representing the text to be justified, and an int width, indicating the width (in letters) that each line except the last must have. You should always place at least two words on each line except the last (the constraints ensure this is possible). The constraints will ensure that the return is unique. You should return a String[], each element of which represents a single line. Keep in mind that the last line of the return will not be justified. Words within a line should be separated by single spaces, and there should be no leading or trailing spaces.
 

Definition

    
Class:Justify
Method:justify
Parameters:String[], int
Returns:String[]
Method signature:String[] justify(String[] paragraph, int width)
(be sure your method is public)
    
 

Notes

-A word is a sequence of non-space characters that is not a substring of any other sequence of non-space characters.
 

Constraints

-paragraph will contain between 1 and 50 elements, inclusive.
-Each element of paragraph will contain between 1 and 50 characters ('a'-'z', 'A'-'Z', '.', ',', '-' and ' ').
-No element of paragraph will contain leading, trailing, or double spaces.
-width will be between 10 and 80, inclusive.
-There will be a way to place the words in paragraph such that each line except the last has at least two words.
-The best return will be unique.
 

Examples

0)
    
{"the quick brown fox jumps over the lazy dog"}
13
Returns: { "the quick",  "brown fox",  "jumps over",  "the lazy dog" }
With the width this small, the best we can do is to have some spaces that are 5 times as wide as letters. In the first line, for instance, there are 8 letters, and only one space. Note that the last line need not be justified.
1)
    
{"the quick brown fox", "jumps over the lazy dog"}
20
Returns: { "the quick brown fox",  "jumps over the lazy",  "dog" }
We can do much better with the same words, but a larger width. In this case, the widest space is only 1.3333 times as wide as a letter.
2)
    
{"the"}
80
Returns: { "the" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Inversions

Sorting



Used in:

TCCC05 Qual 2

Used as:

Division I Level Three

Writer:

vorthys

Testers:

PabloGilberto , lbackstrom

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3492

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6524&pm=3492

Problem Statement

    

An important metric in the theory of sorting is the number of inversions in a sequence. An inversion is any pair of elements that are out of order, meaning that the earlier element in the sequence has a larger value than the later element in the sequence. For example, the sequence

   3 1 4 2 5
has three inversions: 3-1, 3-2, and 4-2.

Given integers n and inv, you are to return a permutation of the sequence 1,...,n that has exactly inv inversions. If it is not possible to create a permutation that has inv inversions, return the empty sequence. If there is more than one permutation that has exactly inv inversions, return the lexicographically earliest. A permutation P is lexicographically earlier than a permutation Q if, at the first index at which the permutations differ, the element in P is smaller than the element in Q.

 

Definition

    
Class:Inversions
Method:createExample
Parameters:int, int
Returns:int[]
Method signature:int[] createExample(int n, int inv)
(be sure your method is public)
    
 

Constraints

-n is between 1 and 1000, inclusive.
-inv is between 0 and 1000000, inclusive.
 

Examples

0)
    
3
0
Returns: { 1,  2,  3 }
The only way for the sequence to have no inversions is for it to be in increasing order.
1)
    
4
6
Returns: { 4,  3,  2,  1 }
A sequence in decreasing order.
2)
    
4
10
Returns: { }
There is no way to get 10 inversions with only 4 elements.
3)
    
14
21
Returns: { 1,  2,  3,  4,  5,  6,  7,  14,  13,  12,  11,  10,  9,  8 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PackageShipping

Dynamic Programming, Graph Theory



Used in:

TCCC05 Round 3

Used as:

Division I Level Two

Writer:

lars2520

Testers:

PabloGilberto , Yarin , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3481

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6530&pm=3481

Problem Statement

    Shipping is a complicated business, particularly when you are shipping fragile items. To do well, you need to deliver packages quickly, at a low cost, and without breaking them. To this end, you would like software to help you send a package, given the package's cost and the maximum delivery time. There are a number of different routes that are continually traversed by your fleet of trucks. Each route takes a certain amount of time, and it costs a certain amount to send a package along that route. Furthermore, there is a probability associated with each route indicating the percent chance that a package will be damaged along that route.



As the shipping company, you must pay the cost of an item if it is damaged during shipping. Your goal is to find the way to ship an item with the lowest expected cost. For example, if one shipping plan has a cost of X, but a 50% probability of damaging an item, it might end up with a higher expected cost than a plan that has a cost of 2X but only a 5% chance of damaging an item.



You will be given a String[], routes, each element of which represents a single route and will be formatted as

"ORIGIN DESTINATION TIME COST PROBABILITY"

where ORIGIN and DESTINATION are city codes (sequences of uppercase letters), TIME is an integer between 1 and 50, COST is an integer between 1 and 20, and PROBABILITY is a real number between 0 and 10, all ranges inclusive. The inputs origin and destination are the starting and ending points for the package to be delivered. time is the maximum allowed delivery time, and is in the same units as TIME in routes. cost is the cost of the package, and is in the same units as COST in routes. You should find the shipping plan with the lowest expected cost, and return that cost as a double.
 

Definition

    
Class:PackageShipping
Method:ship
Parameters:String[], String, String, int, int
Returns:double
Method signature:double ship(String[] routes, String origin, String destination, int time, int packageCost)
(be sure your method is public)
    
 

Notes

-A route from A to B does not imply a route from B to A.
-You may assume that there is no waiting time when a package is transferred from one route to another.
-You won't know that a package is damaged until it reaches its destination, so you must still send it all the way to the destination, even if it is damaged at the beginning of the trip.
 

Constraints

-routes will contain between 1 and 50 elements, inclusive.
-Each element of routes will be formatted as "ORIGIN DESTINATION TIME COST PROBABILITY", with no double, leading or trailing spaces.
-Each element of routes will contain between 9 and 50 characters, inclusive.
-ORIGIN and DESTINATION will each be sequences of uppercase letters ('A'-'Z')
-In no element of routes will ORIGIN equal DESTINATION.
-TIME will be an integer between 1 and 50, inclusive, with no leading zeros.
-COST will be an integer between 1 and 20, inclusive, with no leading zeros.
-PROBABILITY will be between 0 and 10, inclusive, and will be formatted as a sequence of 1 or more digits ('0'-'9') and an optional decimal point (extra leading/trailing zeros allowed).
-origin will be a sequence of uppercase letters matching an ORIGIN in some element of routes.
-destination will be a sequence of uppercase letters matching a DESTINATION in some element of routes.
-time will be between 1 and 100, inclusive.
-packageCost will be between 1 and 1,000,000,000, inclusive.
-There will be some way to deliver the package in the given amount of time or less.
-No two elements of routes will have the same origin and destination.
-origin and destination will not be the same.
 

Examples

0)
    
{"SANFRAN CHICAGO 20 3 0.4",
 "SANFRAN MEMPHIS 30 5 1.0",
 "CHICAGO NEWYORK 15 2 2.0",
 "MEMPHIS NEWYORK 8 6 0.1"}
"SANFRAN"
"NEWYORK"
100
100
Returns: 7.392000000000005
There are two possibilities here. We can ship the package through either CHICAGO or MEMPHIS. If we ship the package through CHICAGO, it will cost us 5, and there will be a 2.392% chance that it will be damaged. If we ship through MEMPHIS, it will cost 11, but there will only be a 1.099% chance of damage. Since the package has a cost of 100, the first option will have an expected cost of 7.392, while the second will have an expected cost of 12.099.
1)
    
{"SANFRAN CHICAGO 20 3 0.4",
 "SANFRAN MEMPHIS 30 5 1.0",
 "CHICAGO NEWYORK 15 2 2.0",
 "MEMPHIS NEWYORK 8 6 0.1"}
"SANFRAN"
"NEWYORK"
100
10000
Returns: 120.90000000000055
Here we have the same shipping routes as example 0, but for a more expensive package. Shipping through CHICAGO will have an expected cost of 5 + 239.2 = 244.2, while MEMPHIS will have an expected cost of 11 + 109.9 = 120.9.
2)
    
{"SANFRAN CHICAGO 20 3 0.4",
 "SANFRAN MEMPHIS 30 5 1.0",
 "CHICAGO NEWYORK 15 2 2.0",
 "MEMPHIS NEWYORK 8 6 0.1"}
"SANFRAN"
"NEWYORK"
36
10000
Returns: 244.20000000000053
In this case, the time constraint forces us to send the package along the more expensive route through CHICAGO.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SantaClaus

Graph Theory, Search



Used in:

SRM 275

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

PabloGilberto , lbackstrom , Yarin , vorthys , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3468

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8072&pm=3468

Problem Statement

     The spirit of Christmas is most apparent in the exchanging of presents! Santa Claus would like software to make this unnecessary. He has already decided which present should be given to each person, but he is wondering if he could make adjustments.

Specifically he has estimated the intrinsic value of each present to each person. He wants software to determine if there is a group of people whose total value would be increased by redistributing the gifts within the group. Some people might end up with a worse present, but the total value is what Santa must consider. If such a group exists, Santa would like to know the size of the smallest such group, and how much the total value of their presents can be increased by.

The intrinsic value of the presents to each person is given in a String[] value. Each character in each element of value is an uppercase letter, with 'A' signifying a value of 1, 'B' a value of 2, etc. The j-th character in the i-th element of value is the value of the j-th present to the i-th person.

The original intent of Santa was to give the first present to the first person, the second present to the second person, etc. Create a class SantaClaus that contains a method exchange that is given the String[] value and returns a int[] containing two elements: the first element is the size of the smallest improvable group, and the second is the amount by which their total value can be increased. Report the largest possible increase in value for a group of that size. If there is no improvable group, return 0 in both elements.

 

Definition

    
Class:SantaClaus
Method:exchange
Parameters:String[]
Returns:int[]
Method signature:int[] exchange(String[] value)
(be sure your method is public)
    
 

Constraints

-value will contain n elements, where n is between 2 and 50 inclusive.
-Each element of value will contain n characters, each being an uppercase letter 'A'-'Z'.
 

Examples

0)
    
{"ABCDE","ABCDE","ABCDE","ABCDE","ABCDE"}
Returns: {0, 0 }
Each present has the same value to everybody, so there is no way to increase the total value by reassigning the presents.
1)
    
{"ABC","BCD","ZAB"}
Returns: {2, 26 }
The third person would really like the first present. So we could exchange presents between the first person and the third person. Previously, the values were 1 (first person) + 2 (third person) = 3. After the exchange the values become 3 (first person) + 26 (third person) = 29. So the net gain is 29-3 = 26.
2)
    
{"BCAAA","ADEAA","AAXYA","AAAKL","EAAAD"}
Returns: {3, 1 }
The first, fourth, and fifth persons can exchange presents, giving up values of 'B', 'K', and 'D' and acquiring values of 'A', 'L', and 'E'. The first person loses net value of 1, but each of the others gains 1.
3)
    
{"VWAAA","ADEAA","AAXYA","AAAKL","EAAAD"}  
Returns: {5, 5 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Triptych

Graph Theory



Used in:

TCCC05 Round 4

Used as:

Division I Level Two

Writer:

vorthys

Testers:

PabloGilberto , lbackstrom , Yarin

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3449

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=6531&pm=3449

Problem Statement

    

You are planning a business trip in which you need to visit clients in three cities. The airline charges a separate rate for each individual leg of your journey. For example, if you are flying from city A to city C, and you land in city B along the way, then you will pay the fare for a flight from A to B plus the fare for a flight from B to C. The airline only sells round-trip tickets, so if you pay for a flight from A to B, then you get a flight from B to A for free, whether you intend to use it or not. You want to calculate the minimum cost needed to fly to your three destination cities and return home.

The prices of each possible flight are given as a String[] fares. The i-th element of fares represents the prices of flights between city i and each of the other cities. In particular, character j of element i represents the price of a flight between city i and city j. Characters with ASCII values between 49 (the character '1') and 122 (the character 'z') represent costs between $10 and $740, respectively. In particular, a character with ASCII value VAL represents the cost 10*(VAL - 48), measured in dollars. The special character '-' indicates that no flights are available between those two cities. For example, if fares contains the Strings

    "-7-"
    "7-A"
    "-A-"
then it costs $70 to travel between cities 0 and 1, and $170 to travel between cities 1 and 2 ('A' has ASCII value 65). There are no direct flights between cities 0 and 2. fares is always symmetric; the cost to travel from city i to city j is always the same as the cost to travel from city j to city i.

The indices of the cities you intend to visit are given in a int[] destinations, which always contains exactly 3 elements. It is possible that more than one client lives in the same city, so the elements of destinations are not necessarily distinct. You live in city 0, and must begin and end your trip there. Calculate and return the minimum cost to visit all three clients, or -1 if it is impossible to visit one or more of the clients.

 

Definition

    
Class:Triptych
Method:minCost
Parameters:String[], int[]
Returns:int
Method signature:int minCost(String[] fares, int[] destinations)
(be sure your method is public)
    
 

Constraints

-fares contains between 3 and 50 elements, inclusive.
-Each element of fares contains exactly N characters, where N is the number of elements in fares.
-Each character in fares is either '-' or has an ASCII value between 49 ('1') and 122 ('z'), inclusive.
-The character '\' (ASCII 92) does not appear in fares.
-Character i of element j of fares is equal to character j of element i, for all indices i and j.
-Character i of element i of fares is '-', for all indices i.
-destinations contains exactly 3 elements.
-Each element of destinations is between 0 and N-1, inclusive.
 

Examples

0)
    
{ "-7-",
  "7-A",
  "-A-" }
{ 1, 2, 1 }
Returns: 240
You fly from city 0 to city 1 for $70, and visit both client 0 and client 2. Then you fly from city 1 to city 2 for $170, and visit client 1. Finally, you return home to city 0, with a layover in city 1.
1)
    
{ "-8--9",
  "8---7",
  "---5-",
  "--5--",
  "97---" }
{ 1, 3, 4 }
Returns: -1
You can reach cities 1 and 4, but you can't get to city 3.
2)
    
{ "-5777",
  "5-555",
  "75-88",
  "758-8",
  "7588-" }
{ 2, 3, 4 }
Returns: 200
You could fly directly to each client's city and return home in between visits for a cost of $210. However, you can make all the visits for only $200 by flying to city 1 and using that as a hub to fly to the other cities.
3)
    
{ "-123",
  "1-45",
  "24-6",
  "356-" }
{ 0, 0, 0 }
Returns: 0
All the clients live in your own city, so no flights are necessary.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WalkingHome

Graph Theory



Used in:

SRM 222

Used as:

Division I Level Two

Writer:

timmac

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3444

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5868&pm=3444

Problem Statement

    

Johnny has to walk home from school, and wants to map out the best route to take, so that he has to cross as few streets as possible.

You are given a String[] map that maps the roadway layout of Johnny's town. The location of Johnny's school is designated with a 'S' character, and the location of Johnny's home is designated with a 'H' character. North-South roads are denoted by a '|' character, while East-West roads are denoted by a '-' character. Intersections, which can never be crossed, are indicated by '*' characters. Fences, indicated by a 'F' character, can also never be crossed. All other areas are indicated by '.' characters; Johnny can walk freely over these areas.

For maximum safety, Johnny may only walk directly across a road, perpendicular to the traffic, never diagonally. All of Johnny's movements, onto and off of a road, and walking around town, should be in one of the four cardinal directions. Johnny may, however, cross roads that are multiple lanes wide, and doing so only counts as a single crossing. Two or more adjacent || characters are always considered to be a single road, and this works similarly for '-' characters that appear adjacent vertically.

For instance, the following requires only a single crossing, since it's a single two-lane road:

S.||.H

Also, a situation such as the following leaves Johnny with no safe way to walk home, since he cannot cross the road diagonally, and can only step onto and off a road in a direction perpendicular to the road:

S||
||H

Also notice that because Johnny can never move diagonally, in the following case, Johnny cannot get home:

S.F
.F.
F.H

You are to return an int indicating the fewest number of times Johnny must cross the street on his way home. If there is no safe way for Johnny to get home, return -1.

 

Definition

    
Class:WalkingHome
Method:fewestCrossings
Parameters:String[]
Returns:int
Method signature:int fewestCrossings(String[] map)
(be sure your method is public)
    
 

Notes

-If a street is more than one unit wide, it still only counts as a single crossing.
 

Constraints

-map will contain between 1 and 50 elements, inclusive.
-Each element of map will contain between 1 and 50 characters, inclusive.
-Each element of map will contain only the characters '.', '-', '|', '*', 'F', 'S', 'H'.
-There will be exactly one occurrence each of 'S' and 'H' in map.
-Each element of map will contain the same number of characters.
 

Examples

0)
    
{"S.|..",
 "..|.H"}
Returns: 1
Here, Johnny lives right across the street from the school, so inevitably, he's crossing the street once to get home.
1)
    
{"S.|..",
 "..|.H",
 "..|..",
 "....."}
Returns: 0
Similar to above, but since the road has a dead end (maybe even a cul-de-sac at the end), Johnny can get home without actually having to cross the road.
2)
    
{"S.||...",
 "..||...",
 "..||...",
 "..||..H"}
Returns: 1
Notice here that even though it's a 2-lane highway, it only counts as a single crossing.
3)
    
{"S.....",
 "---*--",
 "...|..",
 "...|.H"}
Returns: 1
Here, Johnny could go down across the street and then right across another street to his house. However, if he first goes to the right before crossing down, he will only cross 1 street.
4)
    
{"S.F..",
 "..F..",
 "--*--",
 "..|..",
 "..|.H"}
Returns: 2
Similar to above, but because there's a fence around the school, Johnny has no choice but to cross twice.
5)
    
{"H|.|.|.|.|.|.|.|.|.|.|.|.|.",
 "F|F|F|F|F|F|F|F|F|F|F|F|F|-",
 "S|.|.|.|.|.|.|.|.|.|.|.|.|."}
Returns: 27
Poor Johnny lives so close to school, but that fence makes him cross the street quite a bit just to get home.
6)
    
{"S-H"}
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LakeDepth

Graph Theory



Used in:

TCO04 Finals

Used as:

Division I Level One

Writer:

lars2520

Testers:

PabloGilberto , lbackstrom , Yarin , legakis

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3101

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5886&pm=3101

Problem Statement

    Given the elevations of a plot of land, determine the deepest lake that could exist on the plot. Assume that water will flow off the edge of the plot, and therefore a lake will not cover any land on the border. A lake could form at a location up to level h so long as there is no path of horizontal or vertical steps from the lake to the edge of the plot that is completely below h. For example, consider the following plot:

  5255
  5225
  5525
  5515
  5555
A lake will form up to level 2 where the 1 is.



You will be given a String[], plot, where the ASCII value of plot[i][j] represents the height of the land at location (i,j). Your task is to determine the deepest lake that could form in the plot, where the depth of a lake is the largest difference between the lake height and the height of the land under the water.
 

Definition

    
Class:LakeDepth
Method:depth
Parameters:String[]
Returns:int
Method signature:int depth(String[] plot)
(be sure your method is public)
    
 

Notes

-If no lake can form, return 0.
 

Constraints

-plot will contain between 3 and 50 elements, inclusive.
-Each element of plot will contain between 3 and 50 characters, inclusive.
-Each element of plot will be the same length.
-Each character in plot will have an ASCII value between 32 and 126, inclusive.
 

Examples

0)
    
 {"5255",
  "5225",
  "5525",
  "5515",
  "5555"}
Returns: 1
This is the example above.
1)
    
 {"55555",
  "59995",
  "59595",
  "59195",
  "59995",
  "55555"}
Returns: 8
A lake of height '9' will form in the center of this plot.
2)
    
 {"55555",
  "59995",
  "59A95",
  "59A95",
  "59995",
  "55555"}
Returns: 0
No lake may form here, as 'A' has a higher value that '9'.
3)
    
{"55555",
 "52335",
 "53315",
 "45555"}
Returns: 4

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Spanning

Brute Force, Graph Theory



Used in:

TCO04 Semifinal 3

Used as:

Division I Level Two

Writer:

lars2520

Testers:

PabloGilberto , legakis , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3099

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5884&pm=3099

Problem Statement

    Given a connected graph with nodes nodes, where each edge is undirected and has both a length and a cost, your task is to pick a subset of the edges such that the graph is still connected, the minimum distance between each pair of nodes is less than or equal to threshold, and the total cost is minimized. You should return this minimum cost. The graph will be given as a String[], g, each element of which represents an edge in the form "u v length cost", where u and v are the zero-based indices of the two nodes connected by this edge. For example, consider the following input:

nodes = 3

threshold = 5

g = {"0 1 4 1","0 2 3 2","1 2 1 4"}

If we select the first and second edges, then the distance between nodes 1 and 2 ends up being 7, greater than our threshold. However, if we pick the first and third edges, the distance between all pairs of nodes is 5 or less, and the cost is minimized (picking the second and third edges would cost more). Thus, we return the cost of these two edges, 5.
 

Definition

    
Class:Spanning
Method:cost
Parameters:String[], int, int
Returns:int
Method signature:int cost(String[] g, int nodes, int threshold)
(be sure your method is public)
    
 

Constraints

-g will contain between 1 and 18 elements, inclusive.
-nodes will be between 2 and 10, inclusive.
-threshold will be between 1 and 1000, inclusive.
-Each element of g will be formatted as "u v length cost", where u, v, length and cost are all integers with no extra leading zeros.
-Each u and v will be between 0 and nodes-1, inclusive.
-Each length and cost will be between 1 and 100, inclusive.
-No two elements of g will refer to edges between the same pair of nodes.
-In each element of g, u will not equal v.
-If you use all of the edges, the graph will be connected, and the minimum distance between each pair of nodes will be less than or equal to threshold.
 

Examples

0)
    
{"0 1 4 1","0 2 3 2","1 2 1 4"}
3
5
Returns: 5
1)
    
{"2 3 7 1",
 "3 1 9 1",
 "1 0 8 1",
 "3 0 1 5",
 "1 2 5 7",
 "0 2 8 4"}
4
1000
Returns: 3
With the threshold this high, we just need to find the cheapest way to connect all the nodes. It turns out that the first, second and third edges do this cheapest.
2)
    
{"2 3 7 1",
 "3 1 9 1",
 "1 0 8 1",
 "3 0 1 5",
 "1 2 5 7",
 "0 2 8 4"}
4
10
Returns: 14
With the same graph, but a lower threshold, the best edges to use are the first, third, fourth, and fifth.
3)
    
{"0 1 5 5"}
2
100
Returns: 5

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ComboBoxKeystrokes

Dynamic Programming



Used in:

SRM 225

Used as:

Division I Level Two

Writer:

Kawigi

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3098

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5871&pm=3098

Problem Statement

    

A "combo box", "choice", or "select box" is a graphical component found in many applications where the current selection is displayed with an arrow on the right side that you can push on to see all the options that can be selected. You probably selected an item from a combo box to open this problem.

A common behavior when you try to use a combo box with your keyboard is that the first element in the combo box that starts with the typed character (case insensitive) after the currently selected item becomes selected. If there are no elements that start with that character after the currently selected item but there is one before it, the first element in the combo box that starts with that character is selected. If no items in the combo box start with that letter, the currently selected element stays selected.

A well-designed combo box will allow you to navigate by keyboard from any selection to any other selection in a minimal number of keystrokes.

You will be given the selectable contents of the combo box as a String[] called elements. You are to write a program to find the maximum number of keystrokes absolutely necessary to get to any element from any element in the combo box.

 

Definition

    
Class:ComboBoxKeystrokes
Method:minimumKeystrokes
Parameters:String[]
Returns:int
Method signature:int minimumKeystrokes(String[] elements)
(be sure your method is public)
    
 

Notes

-The elements in elements may not be unique.
-It takes zero keystrokes to get from an element to itself.
-The keystrokes made are case-insensitive, meaning that if 'a' is hit, the first 'a' or 'A' after the current selection will be selected, whichever occurs first.
-In most real applications, you could use the arrow keys as well as the letter keys. However, in this problem, you may only use letter keys.
 

Constraints

-elements will have between 1 and 50 elements, inclusive.
-There will be between 1 and 50 characters in each element of elements, inclusive.
-Each element in elements will consist of upper- and lower-case letters and spaces, but will not start with a space.
 

Examples

0)
    
{"alpha","beta","gamma","delta"}
Returns: 1
Since all the elements in the combo box start with different letters, you can get to any element with one keystroke!
1)
    
{"kyky","kalinov","kalmakka","Kavan","Kawigi","kaylin","Klinck","krijgertje","kupo"}
Returns: 8
This list of fine coders can only be traversed one at a time, because all elements start with "K".
2)
    
{"a","b","c","b","d","b","e","b","f"}
Returns: 2
The b's in this list would be an inconvenience, if you couldn't always instantly skip to the entry before them, making them all no more than 2 keystrokes away.
3)
    
{"apple","Boy","CaRD","Dog","egG","FruiT",
 "Grape","hand","Ant","eagle","ice cream",
 "air","East","Exit","Door","camerA","bad",
 "fast","Zealot","internAtional","Bead",
 "Bread","Exit","fast", "actiVe","Cats",
 "beast","Alligator","drag","castle",
 "clean","iLlEgAl","crab","Free Willy",
 "first","dean","Fourth of July","King",
 "fellow","FrEaK","Elephant","bird","Bible",
 "creep","create","Deal","eEl","entrance",
 "cream","Fleece"}
Returns: 4

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ImageSteganography

Encryption/Compression, Simple Math, String Manipulation



Used in:

SRM 225

Used as:

Division II Level Three

Writer:

Kawigi

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3094

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5871&pm=3094

Problem Statement

    

Steganography is a method of cryptography where a message or entire document can be hidden inside of another file or image which shows no evidence that there is data hidden in it. Typically, the message or document to be sent is first encrypted and compressed, and then combined with an existing file in the bits that are less significant.

For example, the encrypted, compressed file could be combined with a bitmap image, and each byte of the file could be encrypted into the lowest two bits of 4 pixel values. The result would be that there is a 1/4 chance that a given pixel is completely unchanged, and a 3/4 chance that it is changed, but by such a small amount that it is essentially undetectable.

While it is not as secure or efficient, you could quite easily encrypt a message into a bitmap image with no encryption or compression, and your message would be protected by the fact that the image has no distinguishable traits that suggest that a message is hidden in it. You will be given an "image" and you will encode a given message into it and return the new image. The returned image should be in the same format as the original image.

The image will be in the format of a String[] where each three digits represent a number from 0 to 255, inclusive (leading zeros will be added as necessary), which is a pixel value in the image. You will also be given a String, message which contains the message you would like to encode into the image. You will first encode the message into numbers representing the characters in the message - spaces will be 0, 'A'-'Z' will be 1-26, 'a'-'z' will be 27-52, '0'-'9' will be 53-62, and 63 will be used for any space after the message. All these numbers can be represented in binary with 6 digits. You will put each pair of bits (representing a number between 0 and 3) into the lowest two bits of the values in the image. For each character, you will put in the lowest two bits, then the middle two, then the highest two, and then continue to the next character. You will put them in the lowest two bits of the first pixel on the first row, then the second pixel on the first row, and so on until you get to the end of the first row, then the first pixel on the second row, and so on. Once you are out of characters, continue substituting the lowest two bits of each pixel value as if the current character were represented by number 63.

 

Definition

    
Class:ImageSteganography
Method:encode
Parameters:String[], String
Returns:String[]
Method signature:String[] encode(String[] image, String message)
(be sure your method is public)
    
 

Notes

-The number of pixels in image may not be a multiple of 3, but you should continue inserting the message as if there was room to finish the last character.
 

Constraints

-image will have between 1 and 50 elements, inclusive.
-The number of characters in each element of image will be a multiple of 3 between 3 and 48, inclusive.
-message will have between 1 and 50 characters, inclusive.
-There will be enough room in image to encode message.
-Each element of image will be made up of 3-digit numbers between 0 and 255, inclusive, padded with zeros if necessary.
-The characters in message will be spaces, numbers, and upper- and lower-case letters.
 

Examples

0)
    
{"255123212001201222"}
"hi"
Returns: { "254120214003200222" }
This single-pixel-thick image is still big enough to encode this message.
1)
    
{"255123212","001201222"}
"hi"
Returns: { "254120214",  "003200222" }
Same message, but with the second letter on a different row.
2)
    
{"123234213001023213123145",
 "222111121101213198009",
 "121122123124125",
 "132212093039",
 "213110"}
 "Hello 1"
Returns: 
{ "120234212003023213122145",
 "222110121102213198010",
 "120120120126125",
 "135215095039",
 "215111" }
Notice that the image doesn't strictly need to be rectangular, letters from the message might need to wrap to multiple lines, and the whole image may not have a multiple of 3 "pixels".

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LeapAge

Simple Search, Iteration



Used in:

SRM 220

Used as:

Division II Level One

Writer:

Kawigi

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3091

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5866&pm=3091

Problem Statement

    

Your friend was born on "leap day" and has always been troubled by the fact that he just turned 24 this year on his 5th birthday. You would like to write him a nice program for his birthday to help him and other leap-day-born people keep track of how many birthdays they've had so far.

You will be given two years as ints, year represents the current year and born represents the year the person was born. You are to return the number of leap days that have occurred in that time span, not including the first year if it is a leap year, but including the current year if it's a leap year.

A leap year is any year that is a multiple of 4, unless it is divisible by 100 and not 400. For example, 1984 was a leap year, but 1900 wasn't, because it was divisible by 100 and not 400. 2000 was a leap year, because it was divisible by both 100 and 400.

 

Definition

    
Class:LeapAge
Method:getAge
Parameters:int, int
Returns:int
Method signature:int getAge(int year, int born)
(be sure your method is public)
    
 

Notes

-It is possible that year and born are not actually leap years.
 

Constraints

-year and born will both be between 1582 and 10000 (1582 is when the Gregorian Calendar started, so there were no leap years before then).
-year will be greater than born.
 

Examples

0)
    
2004
1980
Returns: 6
This is the case in the first paragraph of the problem statement.
1)
    
10000
1582
Returns: 2042
This is about as old as you get in this problem. Note that while the Gregorian Calendar (and therefore, leap years) started in 1582, 1582 wasn't a leap year.
2)
    
2007
1981
Returns: 6
You really don't know why your lying friend asked you to write this...
3)
    
1981
1980
Returns: 0
4)
    
1984
1983
Returns: 1
5)
    
9700
5795
Returns: 947

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Supply

Graph Theory



Used in:

TCO04 Wildcard

Used as:

Division I Level Three

Writer:

lars2520

Testers:

PabloGilberto , lbackstrom , Yarin , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3082

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5885&pm=3082

Problem Statement

    As the manager of a large company, you have a number of factories, and a number of retail stores. Each factory has a location given as (x,y), and some output capacity. Each store also has a location given as (x,y), and a demand specifying the number of products it must receive. Products are produced at the factories, and sent to the stores, and it is important that the stores receive the number of products they ask for. Recently, the factories have not been able to keep up with demand, so you are planning to build a new one. However, you are not sure where the best place to build it is. There is a constant cost of shipping per product, per unit of distance, which we'll call C. Hence, shipping 3 products from (0,0) to (3,4) costs 3*sqrt(3*3+4*4)*C = 15*C. Your new factory will have an output capacity exactly equal to the current difference between the sum of the capacities of all the factories, and the sum of the demands of all the stores. Your task is, assuming an optimal shipping plan, determine the best location to place the new factory.



A String[], factories, will specify the location and capacity of each factory in the format "X Y CAPACITY", where X, Y and CAPACITY are integers. Another String[], stores, will specify the locations and demands of the stores in the format "X Y DEMAND", where X, Y and DEMAND are integers. You should return the optimal factory location as a int[] with two elements, x and y, in that order.
 

Definition

    
Class:Supply
Method:newFactory
Parameters:String[], String[]
Returns:int[]
Method signature:int[] newFactory(String[] factories, String[] stores)
(be sure your method is public)
    
 

Notes

-The location of the new factory must have integral coordinates.
-There may be multiple factories or stores at the same location.
-The constraints ensure that the return is unique.
 

Constraints

-stores will contain between 1 and 10 elements, inclusive.
-factories will contain between 1 and 4 elements, inclusive.
-Each X and Y in stores and factories will be between 0 and 10, inclusive.
-Each CAPACITY and DEMAND will be between 1 and 10, inclusive.
-There will be no extraneous leading zeros or extra spaces in either input.
-The total DEMAND will exceed the total CAPACITY.
-The location providing the minimum cost will be unique, and there will be no other locations that have costs within 1E-3*C of that minimum.
 

Examples

0)
    
{"4 0 10"}
{"5 0 7","10 0 8"}
Returns: { 10,  0 }
There are two stores, with demands of 7 and 8. The single existing factory has a capacity of 10, so our new factory must have a capacity of 5. The best place to put the factory is (10,0), the same spot as the store. Then, we have to ship 3 units from the existing factory to (10,0), and 7 units to (5,0). Thus, our total cost is 7*1*C + 3*6*C = 25*C.
1)
    
{"0 0 1"}
{"5 5 7","10 10 8","10 0 5"}
Returns: { 7,  6 }
Notice that the optimal factory placement is not always at the same location as a store. The total cost here is about 92.485*C.
2)
    
{"0 0 10","0 10 10","10 0 10","10 10 10"}
{"0 0 8",
 "1 1 8",
 "2 2 4",
 "3 3 9",
 "4 4 9",
 "5 5 8",
 "6 6 1",
 "7 7 5",
 "8 8 2",
 "9 9 10"}
Returns: { 3,  3 }
3)
    
{"3 3 10","10 7 7"}
{"6 2 10","2 6 2","7 1 9"}
Returns: { 7,  1 }
4)
    
{"2 8 10","0 1 9","6 4 10","4 8 10"}
{"8 10 9","8 5 2","5 4 7","6 6 7","9 10 3",
 "6 8 7","5 2 6","6 9 2","6 3 9","10 10 9"}
Returns: { 9,  10 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Reconstruct

Brute Force, Recursion



Used in:

SRM 218

Used as:

Division I Level Two

Writer:

lars2520

Testers:

PabloGilberto , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3057

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5864&pm=3057

Problem Statement

    You have collected a number of data points, each consisting of an ordered triple of three integers. Unfortunately, you've lost the original data. However, before you lost the data, you calculated the Euclidean distances between each pair of points and recorded the square of each distance. Given the distances as a String[], dists, you are to find the original data points, if possible. Each element of dists will be formatted as a single space delimited list of integers. The ith integer of the jth element of dists will represent the square of the distance between the ith and jth points.



You should return a String[], the ith element of which represents the the ith data point as 3 single space delimited integers. Since distances are preserved under translation and rotation, the first element of the return should always be "0 0 0", and the second element should consist of 3 non-negative integers sorted in non-descending order. If there are multiple such returns, pick the one that is lexicographically first. For the purposes of this problem, one return is before another lexicographically if it has a lower integer in the first location for which the two differ. In other words, find the first element of the return that is different between the two, and then find the first integer in the two elements that differ, and compare them. If there is no set of points that could generate the given distances, return an empty String[].
 

Definition

    
Class:Reconstruct
Method:findPoints
Parameters:String[]
Returns:String[]
Method signature:String[] findPoints(String[] dists)
(be sure your method is public)
    
 

Constraints

-dists will contain between 1 and 20 elements, inclusive.
-Each element of dists will contain between 1 and 50 characters, inclusive.
-Each number in dists will be an integer between 0 and 1000, inclusive, with no extra leading zeros.
-Each element of dists will contain the same number of integers as there are elements of dists, separated by single spaces.
-In dists, integer i of element j will equal integer j of element i.
-In dists, integer i of element i will equal 0.
 

Examples

0)
    
{"0 1","1 0"}
Returns: { "0 0 0",  "0 0 1" }
1)
    
{"0 2 2","2 0 2","2 2 0"}
Returns: { "0 0 0",  "0 1 1",  "-1 0 1" }
2)
    
{"0 33 25","33 0 84","25 84 0"}
Returns: { "0 0 0",  "1 4 4",  "3 -4 0" }
3)
    
{"0 15","15 0"}
Returns: { }
There are no three integers the sum of whose squares is 15.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GetSubsequence

Dynamic Programming



Used in:

TCO05 Round 4

Used as:

Division I Level Three

Writer:

AdminBrett

Testers:

PabloGilberto , lbackstrom , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3053

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8036&pm=3053

Problem Statement

    Given a String s, we will first collect all distinct positive length subsequences of s, and place them in a list L. A subsequence of s is obtained by deleting 0 or more characters. Next, sort L into ascending order by length. Where ties occur, break them lexicographically. Here uppercase letters occur before lowercase letters. Finally, return the String in position pos % k (0-based), where k is the number of elements in L, and % is the modulus operator.
 

Definition

    
Class:GetSubsequence
Method:getAt
Parameters:String, String
Returns:String
Method signature:String getAt(String s, String pos)
(be sure your method is public)
    
 

Constraints

-s will contain between 2 and 50 characters inclusive.
-Each character in s will be a letter ('A'-'Z','a'-'z').
-pos will be an integral value between 0 and 2^63 - 1 inclusive.
-pos will not have extra leading zeros.
 

Examples

0)
    
"ABCD"
"14"
Returns: "ABCD"
"ABCD" is the last of the 15 subsequences in L.
1)
    
"ABCD"
"19203410239121"
Returns: "ABD"
19203410239121 % 15 = 11.
2)
    
"AAAAAAAAAAAA"
"10"
Returns: "AAAAAAAAAAA"
3)
    
"AbcdAbcdAbcd"
"39283423984923"
Returns: "AbAbdbd"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LeftmostDerivation

String Parsing



Used in:

TCO04 Wildcard

Used as:

Division I Level Two

Writer:

AdminBrett

Testers:

PabloGilberto , lbackstrom , Yarin

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3051

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5885&pm=3051

Problem Statement

    In a Context-Free Grammar, strings are transformed into other strings during a process called a derivation. In our notation, one step of a derivation occurs when an uppercase letter ('A'-'Z') is turned into a string (possibly empty) of uppercase and lowercase letters ('A'-'Z', 'a'-'z'). For example,
     ZaBcD -> ZagHgcD -> ZagHgcF -> ZaggcF -> Zaggcq 
is a derivation transforming ZaBcD into Zaggcq. A derivation is called leftmost if every derivation step replaces the leftmost uppercase letter. Assuming all valid derivation steps are at your disposal, return the leftmost derivation with the smallest number of steps transforming start into finish. Since all possible derivation rules can be used, during each step, choose the leftmost capital letter, and change it to whichever string you want. If there are multiple possible smallest leftmost derivations, return one that comes first lexicographically. Here smallest is measured by the number of steps. To compare two derivations lexicographically, concatenate all of their intermediate strings, and then compare them. As in ASCII, uppercase letters occur lexicographically before lowercase letters. The returned value should be a String[] containing the sequence of intermediate strings, in the order they are created. Element 0 must be start, and the last element must be finish (see the examples for further clarification). If no leftmost derivation is possible, return an empty String[].
 

Definition

    
Class:LeftmostDerivation
Method:getDeriv
Parameters:String, String
Returns:String[]
Method signature:String[] getDeriv(String start, String finish)
(be sure your method is public)
    
 

Constraints

-start will contain between 1 and 50 characters inclusive.
-Each character in start will be an uppercase or lowercase letter ('A'-'Z','a'-'z').
-finish will contain between 1 and 50 characters inclusive.
-Each character in finish will be an uppercase or lowercase letter ('A'-'Z','a'-'z').
-start and finish will be distinct.
 

Examples

0)
    
"ZaBcD"
"Zaggcq"
Returns: { }
Although a derivation was shown in the problem statement, there is no leftmost derivation that works.
1)
    
"AH"
"ABCDEFGH"
Returns: { "AH",  "ABCDEFGH" }
Here we replace A with ABCDEFG.
2)
    
"ABC"
"abc"
Returns: { "ABC",  "BC",  "C",  "abc" }
There are numerous leftmost derivations that take 3 steps, so return the one that occurs first lexicographically.
3)
    
"AaA"
"aAaa"
Returns: { "AaA",  "aA",  "aAaa" }
Firstly, we delete the leftmost A by replacing it with the empty string. Next we replace the remaining A with Aaa.
4)
    
"AaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
Returns: 
{ "AaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aaaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aaaaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aaaaaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aaaaaaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aaaaaaaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aaaaaaaaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aaaaaaaaaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aaaaaaaaaaAaAaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aaaaaaaaaaaAaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aaaaaaaaaaaaAaAaAaAaAaAaAaAaAaAaAaAa",
 "aaaaaaaaaaaaaAaAaAaAaAaAaAaAaAaAaAa",
 "aaaaaaaaaaaaaaAaAaAaAaAaAaAaAaAaAa",
 "aaaaaaaaaaaaaaaAaAaAaAaAaAaAaAaAa",
 "aaaaaaaaaaaaaaaaAaAaAaAaAaAaAaAa",
 "aaaaaaaaaaaaaaaaaAaAaAaAaAaAaAa",
 "aaaaaaaaaaaaaaaaaaAaAaAaAaAaAa",
 "aaaaaaaaaaaaaaaaaaaAaAaAaAaAa",
 "aaaaaaaaaaaaaaaaaaaaAaAaAaAa",
 "aaaaaaaaaaaaaaaaaaaaaAaAaAa",
 "aaaaaaaaaaaaaaaaaaaaaaAaAa",
 "aaaaaaaaaaaaaaaaaaaaaaaAa",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BadXML

String Manipulation, String Parsing



Used in:

TCO04 Semifinal 2

Used as:

Division I Level One

Writer:

Yarin

Testers:

PabloGilberto , lbackstrom , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=3041

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5883&pm=3041

Problem Statement

    

XML documents are widely used today to describe many different kinds of data. The primary purpose of XML is to allow people to share textual and numerical data in a structured format across the Internet. Note that the XML document format described in this problem is a simplified version of the actual XML format.

An XML document contains tags and plain text. Tags are used to define blocks within the XML document. A block always begins with a start-tag and ends with a corresponding end-tag. The format of these tags are <tag-name> and </tag-name>, respectively. The tag-name for an end-tag is the same (including case) as the start-tag for the block it closes. All plain text data must be inside at least one block. The plain text will not contain the characters '<', '>' and '/'.

Blocks may be nested, but cannot overlap. So for instance, "<root><data>Hello world</data></root>" and "<root>Hello</root><root>world</root>" are valid XML documents, while "<root><data>Hello world</root></data>" and "<root>Hello</root> <root>world</root>" are not; the first one has overlapping blocks (the tag <data> must end before the outer tag <root> ends), the second has text - a space - outside all blocks (in this problem, spaces are treated just like any other character, see example 2).

Your task is to write a program which formats an XML document, according to the following rules: If a block contains other blocks, the start- and end-tags for that block should be on lines by themselves, and all tags and text inside this block should be indented by 3 spaces per open tag. Otherwise the start- and end-tags should be on the same line, with the textual content of the block (if any) between the tags (and nothing else, except indentation, may appear on this line). See example 0 for clarifications.

Create a class BadXML containing the method format which takes a String[] doc, the XML document, and returns a String[] containing the properly indented XML document. Concatenate the elements in doc to get the full XML document.

 

Definition

    
Class:BadXML
Method:format
Parameters:String[]
Returns:String[]
Method signature:String[] format(String[] doc)
(be sure your method is public)
    
 

Notes

-Spaces are treated like any other character, see example 2.
 

Constraints

-doc will contain between 1 and 50 elements, inclusive.
-Each element in doc will contain between 0 and 50 characters, inclusive.
-The characters in the elements of doc will have ASCII values between 32 and 126, inclusive.
-The characters '<', '>' and '/' will only be used in tags.
-A tag-name will not contain any of the characters '<', '>', '/' or space.
-A tag-name will contain at least one character.
-doc will describe a valid XML document according to the description above, and will contain at least one block.
-The return value will contain at most 100 elements, and no element will contain more than 80 characters.
 

Examples

0)
    
{"<article>",
 "<author>writer</author>",
 "<headline>TopCoder",
 " ",
 "Open 2004</headline>",
 "<ingress>",
 "</ingress>",
 "<paragraph>",
 "TopCoder Open is being held at <st:hotel>",
 "Santa Clara Marriott</st:hotel>",
 "which lies in the northern part of ",
 "<st:state>California</st:state>.",
 "</paragraph>",
 "<paragraph>",
 "&lbr;Image&rbr;",
 "</paragraph>",
 "</article>"}
Returns: 
{ "<article>",
 "   <author>writer</author>",
 "   <headline>TopCoder Open 2004</headline>",
 "   <ingress></ingress>",
 "   <paragraph>",
 "      TopCoder Open is being held at ",
 "      <st:hotel>Santa Clara Marriott</st:hotel>",
 "      which lies in the northern part of ",
 "      <st:state>California</st:state>",
 "      .",
 "   </paragraph>",
 "   <paragraph>&lbr;Image&rbr;</paragraph>",
 "</article>" }

The block surrounded by the paragraph tags contain two nested blocks as well as three plain text strings. All these end up on separate lines. The other plain text strings end up on the same line as the tags in the blocks they are surrounded by.

1)
    
{"<ro","ot>A roo","","t node</r","oot><","root>Anot","her root node</ro","ot>",""}
Returns: { "<root>A root node</root>",  "<root>Another root node</root>" }
An XML document may contain several blocks at the top level.
2)
    
{"<outer_tag>",
 "   <inner_tag>",
 "      Some text",
 "   </inner_tag>",
 "</outer_tag>"}
Returns: 
{ "<outer_tag>",
 "      ",
 "   <inner_tag>      Some text   </inner_tag>",
 "</outer_tag>" }
The indentation in the input is treated as space characters and is not removed.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

grafixMask

Recursion



Used in:

SRM 211

Used as:

Division I Level Two

Writer:

Eeyore

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2998

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5857&pm=2998

Problem Statement

    

Note: This problem statement includes images that may not appear if you are using a plugin. For best results, use the Arena editor.

In one mode of the grafix software package, the user blocks off portions of a masking layer using opaque rectangles. The bitmap used as the masking layer is 400 pixels tall and 600 pixels wide. Once the rectangles have been blocked off, the user can perform painting actions through the remaining areas of the masking layer, known as holes. To be precise, each hole is a maximal collection of contiguous pixels that are not covered by any of the opaque rectangles. Two pixels are contiguous if they share an edge, and contiguity is transitive.

You are given a String[] named rectangles, the elements of which specify the rectangles that have been blocked off in the masking layer. Each String in rectangles consists of four integers separated by single spaces, with no additional spaces in the string. The first two integers are the window coordinates of the top left pixel in the given rectangle, and the last two integers are the window coordinates of its bottom right pixel. The window coordinates of a pixel are a pair of integers specifying the row number and column number of the pixel, in that order. Rows are numbered from top to bottom, starting with 0 and ending with 399. Columns are numbered from left to right, starting with 0 and ending with 599. Every pixel within and along the border of the rectangle defined by these opposing corners is blocked off.

Return a int[] containing the area, in pixels, of every hole in the resulting masking area, sorted from smallest area to greatest.

 

Definition

    
Class:grafixMask
Method:sortedAreas
Parameters:String[]
Returns:int[]
Method signature:int[] sortedAreas(String[] rectangles)
(be sure your method is public)
    
 

Notes

-Window coordinates are not the same as Cartesian coordinates. Follow the definition given in the second paragraph of the problem statement.
 

Constraints

-rectangles contains between 1 and 50 elements, inclusive
-each element of rectangles has the form "ROW COL ROW COL", where: "ROW" is a placeholder for a non-zero-padded integer between 0 and 399, inclusive; "COL" is a placeholder for a non-zero-padded integer between 0 and 599, inclusive; the first row number is no greater than the second row number; the first column number is no greater than the second column number
 

Examples

0)
    
{"0 292 399 307"}
Returns: { 116800,  116800 }
The masking layer is depicted below in a 1:4 scale diagram.


1)
    
{"48 192 351 207", "48 392 351 407", "120 52 135 547", "260 52 275 547"}
Returns: { 22816,  192608 }

2)
    
{"0 192 399 207", "0 392 399 407", "120 0 135 599", "260 0 275 599"}
Returns: { 22080,  22816,  22816,  23040,  23040,  23808,  23808,  23808,  23808 }

3)
    
{"50 300 199 300", "201 300 350 300", "200 50 200 299", "200 301 200 550"}
Returns: { 1,  239199 }
4)
    
{"0 20 399 20", "0 44 399 44", "0 68 399 68", "0 92 399 92",
 "0 116 399 116", "0 140 399 140", "0 164 399 164", "0 188 399 188",
 "0 212 399 212", "0 236 399 236", "0 260 399 260", "0 284 399 284",
 "0 308 399 308", "0 332 399 332", "0 356 399 356", "0 380 399 380",
 "0 404 399 404", "0 428 399 428", "0 452 399 452", "0 476 399 476",
 "0 500 399 500", "0 524 399 524", "0 548 399 548", "0 572 399 572",
 "0 596 399 596", "5 0 5 599", "21 0 21 599", "37 0 37 599",
 "53 0 53 599", "69 0 69 599", "85 0 85 599", "101 0 101 599",
 "117 0 117 599", "133 0 133 599", "149 0 149 599", "165 0 165 599",
 "181 0 181 599", "197 0 197 599", "213 0 213 599", "229 0 229 599",
 "245 0 245 599", "261 0 261 599", "277 0 277 599", "293 0 293 599",
 "309 0 309 599", "325 0 325 599", "341 0 341 599", "357 0 357 599",
 "373 0 373 599", "389 0 389 599"}
Returns: 
{ 15,  30,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  45,  100,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  115,  200,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  230,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  300,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345,  345 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

grafixClick

Simple Math



Used in:

SRM 211

Used as:

Division II Level One

Writer:

Eeyore

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2996

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5857&pm=2996

Problem Statement

    

Note: This problem statement includes an image that may not appear if you are using a plugin. For best results, use the Arena editor.

You have been hired to work on a graphics application called grafix. The interface includes several buttons that the user can click on during a session. One of these is the Save button, which appears in the application window as a rectangle composed of pixels. The location of each pixel is given by a pair of integers that specify the pixel's row number and column number, in that order. Such an integer pair is called the window coordinates of a pixel. Rows are numbered from top to bottom, and columns are numbered from left to right.

The top left corner of the Save button has window coordinates (20, 50), meaning that it is a pixel occupying the 20th row from the top and the 50th column from the left. The bottom right corner of the Save button has window coordinates (39, 99). If the user clicks her mouse on any pixel within or on the border of the rectangle defined by these points, she is considered to have activated the Save button. Below is a magnified image of the Save button, showing the numbers of its rows and columns.

Given a sequence of mouse clicks, your job is to determine which ones have activated the Save button. For each mouse click, the int[] mouseRows contains the row number of its window coordinates, while the int[] mouseCols contains its column number. The values in each int[] are in corresponding order, so the nth element of mouseRows and the nth element of mouseCols make up the window coordinates of the nth mouse click. You are to return a int[] containing, in ascending order, the zero-based index of each mouse click that activates the Save button.

 

Definition

    
Class:grafixClick
Method:checkSaveButton
Parameters:int[], int[]
Returns:int[]
Method signature:int[] checkSaveButton(int[] mouseRows, int[] mouseCols)
(be sure your method is public)
    
 

Notes

-Window coordinates are not the same as Cartesian coordinates. Follow the definition given in the first paragraph of the problem statement.
 

Constraints

-mouseRows contains between 1 and 50 elements, inclusive
-mouseRows and mouseCols each contain the same number of elements
-each element in mouseRows is between 0 and 399, inclusive
-each element in mouseCols is between 0 and 599, inclusive
 

Examples

0)
    
{20, 39, 100}
{99, 50, 200}
Returns: { 0,  1 }
The first click, with window coordinates (20, 99), falls on the top right corner of the Save button. The second click is on the bottom left corner at (39, 50). The third click has window coordinates (100, 200) and falls outside the button.
1)
    
{0, 100, 399}
{0, 200, 599}
Returns: { }
None of these clicks activate the Save button.
2)
    
{30}
{75}
Returns: { 0 }
Bull's-eye!
3)
    
{10, 20, 30, 30, 30, 30, 34, 35, 345}
{10, 20, 30, 50, 60, 80, 34, 35, 345}
Returns: { 3,  4,  5 }
4)
    
{57, 28, 18, 25, 36, 12, 33, 44, 13, 32,
 32, 51, 11, 27, 8, 51, 17, 34, 10, 16,
 47, 57, 20, 57, 32, 14, 13, 37, 10, 16,
 49, 37, 52, 8, 18, 44, 50, 43, 11, 1,
 21, 22, 17, 35, 28, 53, 56, 16, 11, 44}
{146, 22, 41, 88, 123, 99, 43, 110, 25, 64,
 141, 110, 70, 34, 99, 103, 60, 64, 142, 109,
 133, 144, 72, 68, 25, 32, 21, 140, 30, 105,
 32, 72, 114, 97, 35, 131, 103, 110, 133, 81,
 125, 36, 76, 78, 77, 47, 50, 94, 22, 20}
Returns: { 3,  9,  17,  22,  31,  43,  44 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FileFilter

String Manipulation



Used in:

TCO04 Qual 2

Used as:

Division I Level One

Writer:

lars2520

Testers:

PabloGilberto , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2975

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5874&pm=2975

Problem Statement

    You are working on the backend of a system that allows people to upload files. For security reasons, you want to restrict the file extensions of the files they upload. You will be given a String[], extensions, containing a list of allowed extensions. You will also be given a String[], files, containing the names of a number of files. Your task is to return a String[], each element of which is either "ALLOW" or "DENY", corresponding to the elements of files with the same indices. If a filename ends with a period ('.') followed by an allowed extension, ignoring case, then it is to be allowed, otherwise it should be denied.
 

Definition

    
Class:FileFilter
Method:filter
Parameters:String[], String[]
Returns:String[]
Method signature:String[] filter(String[] files, String[] extensions)
(be sure your method is public)
    
 

Constraints

-files will contain between 0 and 50 elements, inclusive.
-extensions will contain between 0 and 50 elements, inclusive.
-Each element of files will contain between 2 and 50 letters ('a'-'z' and 'A'-'Z') and periods.
-The last character of each element of files will be a letter.
-Each element of files will contain at least one period.
-Each element of extensions will contain between 1 and 50 lowercase letters ('a'-'z').
 

Examples

0)
    
{"algorithm.txt","algorithms.html","wingl.exe","yourDoc.PIF","graph.gIf"}
{"txt","html","gif","doc"}
Returns: { "ALLOW",  "ALLOW",  "DENY",  "DENY",  "ALLOW" }
1)
    
{}
{"exe","pif"}
Returns: { }
2)
    
{".bashrc","bash.rc"}
{"rc"}
Returns: { "DENY",  "ALLOW" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GeneticCrossover

Advanced Math



Used in:

TCO04 Qual 3

Used as:

Division I Level Three

Writer:

lars2520

Testers:

PabloGilberto , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2974

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5875&pm=2974

Problem Statement

    In genetics, most large animals have two copies of every gene - one from each parent. In the simplest genetic model, each of the genes takes on one of two forms, dominant or recessive, usually represented by an uppercase and lowercase letter of the same value, respectively ('A' and 'a', for example). The pair of genes typically contributes to the external qualities of the animal in one of two ways. If one or two genes are uppercase, the dominant gene is said to be expressed. If both genes are lowercase, then the recessive gene is said to be expressed.



Additionally, there may be some gene dependencies. If one pair of genes is dependent on another pair of genes, then the first gene may only be expressed dominantly if the gene it depends on is also expressed dominantly. These dependencies are indicated by a int[], dependencies. If element i of dependencies is j, it means that gene i can only be expressed dominantly if gene j also is (both i and j are indexed from 0). If gene j is expressed recessively, then gene i must be also, regardless of the actual genes at position i. If an element of dependencies is -1, it means that the gene is not dependent on any other gene, and is expressed as described in the first paragraph. Chains may exist within dependencies where i depends on j, which in turn depends on k. However, a gene may not depend on itself, and there will be no looping dependencies.



In this problem you are to predict a certain quality about an animal, given N pairs of genes from each of its parents, and some information about those N genes. The first parent's two copies of the genes are given by p1a and p1b, while the second parent's are given by p2a and p2b. For each of the N genes, each parent contributes one of its two genes to its children (characters with the same indices in p1a, p1b, p2a, and p2b correspond to the same gene). For example, if p1a = "ABC" and p1b = "abc", the first parent would contribute an 'A' or an 'a' to its child's first pair of genes, a 'B' or a 'b' to its child's second pair and so on. Similarly, the second parent would also contribute a single gene to its child's first pair of genes, one to its second pair and so on.



Thus, the offspring end up with N genes from each parent. Each pair of corresponding genes contributes in some way to a certain quality we are interested in. If the ith pair of genes is expressed dominantly, we add dom[i] to a running sum (which is initialized to 0), otherwise we add rec[i]. Given that each parent contributes one of its two genes entirely at random (with a 50% chance of either), you are to determine the expected value the offspring will have for the quality we are interested in (the running sum), and return that value.
 

Definition

    
Class:GeneticCrossover
Method:cross
Parameters:String, String, String, String, int[], int[], int[]
Returns:double
Method signature:double cross(String p1a, String p1b, String p2a, String p2b, int[] dom, int[] rec, int[] dependencies)
(be sure your method is public)
    
 

Notes

-Your return must have a relative or absolute error less than 1e-9.
 

Constraints

-Let N be the number of genes, where N is between 1 and 50, inclusive.
-p1a, p1b, p2a and p2b will each contain exactly N characters.
-dom, rec, and dependencies will each contain exactly N elements.
-Corresponding characters of p1a, p1b, p2a and p2b will have the same value (but may be uppercase or lowercase).
-Each element of dependencies will be between -1 and N-1, inclusive.
-dependencies will not contain any cycles.
-Each element of dom and rec will be between -100 and 100, inclusive.
 

Examples

0)
    
"AaaAA"
"AaaAA"
"AaaAA"
"AaaAA"
{1,2,3,4,5}
{-1,-2,-3,-4,-5}
{-1,-1,-1,-1,1}
Returns: -5.0
Since every copy is the same, the animal is guaranteed to have two pairs of "AaaAA". This means that the first and fourth genes will be dominantly expressed, while the others will be recessively expressed. Note that the last gene is dependent on gene 1, which is recessively expressed.
1)
    
"AbegG"
"ABEgG"
"aBEgg"
"abegG"
{5,5,5,5,5}
{1,1,1,1,1}
{-1,0,1,2,3}
Returns: 14.25
Here, we have a chain of dependencies, where gene 1 depends on gene 0, 2 depends on 1, and so on. For the first gene, the animal is guaranteed to get an 'A' from its first parent, and an 'a' from its second parent. This means that gene 0 will be expressed dominantly, contributing 5 to the sum. The next gene has a 75% chance of being expressed dominantly (it will only be expressed recessively if a 'b' comes from each parent). The third gene also has a 75% chance of being expressed dominantly, assuming that the second gene was expressed dominantly. The fourth gene is guaranteed to be expressed recessively, and hence so is the final gene.



This gives us 3 possible scenarios, denoted below, where a 'D' indicates a gene is expressed dominantly, and an 'R' means recessively:

Genes | Sum | Prob
------+-----+-------
DDDRR | 17  | 0.5625
DDRRR | 13  | 0.1875
DRRRR | 9   | 0.25
The expected value is thus 17*0.5625+13*0.1875+9*.25 = 14.25
2)
    
"XyMpdnVsbinDvqBpcWGDLfsmQtZpeirvTmoRmBASfqqrFS"
"xYmpdnVsBINdvQBPCwgDlFSmQTzpEIrVtmoRmbaSfqQRfS"
"XYMpdnvsBINdVQbpCWgDlfSMqTzPeIrVTMOrmbaSfQqrFs"
"XYMpDnVSBIndvQBPCWGDlFsMqtzpEiRVTMORMBASFqQrfS"
{-82,-35,-51,52,87,25,8,27,-12,-10,-63,-36,-95,-35,-98,95,-76,7,36,-35,92,23,-94,
 -31,-30,36,51,-49,-19,-3,19,32,58,82,-36,-87,-54,-17,-40,32,-91,-56,0,-16,70,42}
{-36,77,90,50,83,66,-94,-66,-22,-83,-86,-89,-55,-3,-51,18,-41,-91,91,32,-25,-60,
 5,79,100,85,60,98,55,95,-67,-46,-26,48,-64,16,-36,-95,-54,19,96,79,78,-91,-12,35}
{-1,-1,1,-1,3,-1,-1,1,3,5,4,0,-1,-1,2,8,5,4,-1,10,11,14,3,-1,
15,-1,7,-1,8,-1,-1,15,-1,-1,30,-1,26,26,-1,-1,-1,-1,-1,31,0,3}
Returns: -356.875
3)
    
"fOai"
"Foai"
"fOAI"
"FOAi"
{96,21,-34,-81}
{77,-2,20,25}
{-1,0,-1,-1}
Returns: 44.5

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

NegativePhotoresist

Graph Theory, Math, Search, String Parsing



Used in:

SRM 210

Used as:

Division I Level Three

Writer:

the_one_smiley

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2946

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5856&pm=2946

Problem Statement

    

You are responsible for fabricating a circuit board for an engineering firm. The circuit consists of pinholes (where pins of various components will be inserted) connected by metal traces. For this problem, assume that pinholes can be treated as points in a plane and metal traces can be treated as straight line segments connecting two pinholes.

A highly simplified description of the fabrication process follows. The circuit pattern is cut out of a sheet of opaque material, forming a mask. A sheet of metal is covered with a thin film of material, called negative photoresist, that hardens when exposed to ultraviolet light. The mask is placed over the photoresist and illuminated with ultraviolet light, hardening the photoresist where the light passes through the mask. Finally, the metal sheet is bathed in an etching solution, which destroys the metal except where it is protected by hardened photoresist. The remaining metal forms the circuit.

After a long period of carefully laying out the circuit board, you have the mask prepared. Just before you illuminate the photoresist with ultraviolet light, your boss rushes in and gives you some last minute requirements: the sum of the lengths of the shortest metal trace paths between each pair of pinholes must be under a certain limit, and the board has to be ready by tomorrow. In other words, if you find the shorest path between every pair of connected pins, the sum of the lengths of all these shortest paths must be under the limit. There is no way you can redesign everything in one day, so you decide to improvise. By tilting the mask around its x-axis before you illuminate the photoresist, the circuit will be shrunk along the y-direction; only the projection of the mask on the plane of the photoresist is important since you are shining light through it (assume the light rays are parallel to the z-axis and ignore diffraction effects). Since this also moves the locations of the pins, you want to tilt the mask as little as possible.

Write a class NegativePhotoresist with a method minimumTilt that takes a String[] pinConnections specifying for each pinhole its mask-plane coordinates and its connections to other pinholes and an int limit, and returns as a double the minimum non-negative angle (in radians) the mask must be rotated around the x-axis such that the sum of the lengths of the shortest paths between each pair of pinholes is less than limit. If there is no path between a pair of pinholes, omit that pair from the sum.

Each element of pinConnections corresponds to one pinhole. Element i will begin with a pair of integers specifying the x and y coordinates of pinhole i separated by a single comma. Following this is a space-separated list of zero or more integers specifying the zero-based indices of the pinholes that i connects to. All integers are non-negative and may have leading zeroes. For this problem, pinholes are directly connected if and only if they are specified to connect in pinConnections. In other words, overlapping or coinciding metal traces do not create a connection.

 

Definition

    
Class:NegativePhotoresist
Method:minimumTilt
Parameters:String[], int
Returns:double
Method signature:double minimumTilt(String[] pinConnections, int limit)
(be sure your method is public)
    
 

Notes

-A return value with either an absolute or relative error of less than 1e-9 radians is considered correct.
-There can only be up to one connection between a pair of pinholes. If an index j appears multiple times in element i of pinConnections, there is still only one metal trace between pinholes i and j.
-The sum over all pairs of the shortest path lengths will be minimized when the mask is rotated by Pi / 2 radians.
-Pairs are unordered. The pair (pinhole i, pinhole j) is the same as (pinhole j, pinhole i).
 

Constraints

-The correct answer will be between 0.01 and 1.55, inclusive.
-pinConnections will contain between 2 and 50 elements, inclusive.
-Elements of pinConnections will contain at most 50 characters.
-Elements of pinConnections will be formatted "X,Y P1 P2 P3 ..." (quotes are for clarity) where X and Y are between 0 and 100000 inclusive, and each of the indices Pj will be separated by a single space and will be between 0 inclusive and the number of elements in pinConnections exclusive.
-If pinhole i connects to pinhole j, pinhole j will also connect to pinhole i.
-A pinhole will not connect to itself.
-limit will be between 1 and 1,000,000,000, inclusive.
 

Examples

0)
    
{"3,0 2 3",
"13,0 2 3",
"0,2 0 1",
"8,50 0 1",
"3,100000 5",
"100000,3 4",
"8432,221"}
100835
Returns: 1.4454078077996135
Pinholes 0, 2, 1, and 3 form a cycle (in that order). When the mask is laid flat, the shortest path between pinholes 0 and 1 goes through pinhole 2. However, if the mask is tilted by more than 1.4454039026103331 radians, the shortest path between pinholes 0 and 1 switches to go through pinhole 3. The shortest path between pinholes 2 and 3 always goes through pinhole 0, regardless of the angle. Pinholes 4 and 5 form a separate component that contains only one connection. Pinhole 6 is not connected to anything, and therefore does not influence the total path length.
1)
    
{"3,0 2 3",
"13,0 2 3",
"0,2 0 1",
"8,50 0 1",
"3,100000 5",
"100000,3 4",
"8432,221"}
141601
Returns: 0.010604469396671205
This is the same mask as in Example 0. It only has to be tilted slightly to achieve a total shortest path length of 141601.
2)
    
{"3,0 2 3",
"13,0 2 3",
"0,2 0 1",
"8,50 0 1",
"3,100000 5",
"100000,3 4",
"8432,221"}
100065
Returns: 1.5491503047781332
This is the same mask as in Example 0. It has to be tilted until it is almost standing on its edge to achieve a total shortest path length of 100065.
3)
    
{"76492,66181 1",
"74004,26736 0 14",
"22967,14922",
"5781,62226",
"82836,93961 23",
"87218,72769 19",
"93356,54263 21 23",
"31487,92953",
"4108,40237 25",
"90459,36018 18",
"86769,8014",
"6311,25772 13",
"9507,63470 20",
"30653,48087 11 15",
"84214,63941 1",
"87079,8036 13",
"10892,10164 25 23",
"31650,57394",
"12181,22580 9",
"8820,66849 5",
"63222,10057 12",
"85163,78521 6",
"73264,56781",
"45982,63119 4 6 16",
"96653,33496",
"4728,75705 8 16",
"93821,30582",
"9948,22812"}
2198136
Returns: 1.078664288678656
4)
    
{"26749,31005 7 12 37 22 3 31 18 14 22 43 18 47 27",
"89443,23479 37 20 18 45 4 28 45 48 45 48 42 43",
"26624,91482 8 10 9 47 38 7 26 38 7 15 24 33 13 19",
"74780,3281 5 35 24 0 32 6 7 40 16 44 27 29 27 42",
"64491,34646 12 42 9 10 25 1 14 22 32 28 16 24 49",
"57611,97350 3 6 16 38 37 26 7 46 47 9 34 17 36 33",
"54900,19650 5 41 17 21 3 41 45 9 45 24 7 29 49 33",
"37779,84466 30 37 0 43 36 2 5 45 31 2 3 13 17 6 27",
"68486,19205 2 14 42 44 17 34 25 41 38 43 10 49 11",
"86915,28119 21 31 2 40 31 12 49 41 4 22 5 34 6 46",
"81402,18667 40 2 17 17 18 8 4 12 38 12 15 26 42 12",
"76982,50425 29 29 13 8 36 49 16 27 26 28 27 34 46",
"43766,59005 15 27 0 9 4 22 10 10 49 44 37 10 34 24",
"71619,57051 36 47 48 39 11 45 32 42 30 7 29 2 34",
"95436,51350 8 18 23 22 17 23 22 16 0 48 19 4 24 19",
"18419,71778 29 12 31 23 24 30 36 26 10 18 45 36 2",
"58370,12207 48 33 5 14 19 47 11 28 44 3 18 32 4 46",
"93954,84580 33 21 10 8 47 35 32 6 10 14 43 22 5 7",
"37005,46508 14 29 22 1 10 0 23 37 15 0 31 16 31 41",
"25700,33156 20 25 35 40 38 16 14 22 14 23 27 25 2",
"87882,64415 19 35 35 33 1 24 26 24 34 41 34 31 29",
"80610,20042 9 27 35 28 46 17 37 28 36 37 6 41 34",
"55546,68119 39 18 34 14 12 0 14 9 0 17 39 4 19 27",
"12701,80882 30 32 15 14 37 42 14 47 18 33 47 19 46",
"14048,1355 15 20 20 3 28 42 14 12 2 49 45 25 6 4",
"27482,63293 49 38 45 19 8 39 4 38 47 38 46 19 24",
"48215,66574 35 41 32 30 20 41 5 2 15 35 10 11 49",
"53613,76037 21 12 40 11 42 46 0 3 49 11 19 3 22 7",
"90922,15011 21 30 40 40 40 21 44 24 1 16 4 11 49",
"67445,91022 15 11 35 47 18 11 38 20 13 38 3 32 6",
"93451,40067 41 23 7 28 26 47 42 15 44 49 31 13 31",
"25947,11589 9 15 9 40 39 0 30 7 18 20 30 35 43 18",
"98403,23751 47 37 44 26 23 17 3 13 48 4 16 42 29",
"32918,74706 17 16 39 47 41 20 23 36 5 35 2 6 43 43",
"9851,96894 8 22 44 36 20 21 5 20 12 9 43 13 46 11",
"86305,55072 37 21 26 29 20 3 20 17 19 46 26 33 31",
"66150,16273 45 13 39 7 21 34 15 11 45 39 15 33 5",
"95275,37494 1 35 32 43 7 0 21 23 5 39 44 21 18 12",
"16184,79884 40 25 39 5 8 2 19 10 47 2 25 29 25 29",
"77000,48925 33 22 36 38 25 37 13 31 40 46 40 36 22",
"19246,92639 10 38 9 28 19 28 28 48 31 27 39 39 3",
"37419,96699 30 26 33 6 9 8 45 26 21 6 20 46 18 43",
"65611,72059 8 30 23 4 44 24 10 13 27 3 32 1 48 48",
"78307,80168 37 7 8 17 0 31 34 41 48 33 33 48 1 48",
"35276,57349 8 32 45 34 30 37 28 42 12 46 16 49 3",
"10106,992 36 25 44 41 1 7 36 13 15 6 6 1 24 49 1",
"43647,68652 21 5 35 44 39 27 41 9 25 16 34 23 11",
"7588,43383 32 33 29 2 17 13 30 38 23 16 25 5 23 0",
"39549,20275 16 13 40 14 32 43 1 1 42 43 42 43",
"49470,43071 25 9 8 12 30 11 44 26 28 27 24 45 4 6"}
45315043
Returns: 1.4635199471353126

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

IPConverter

Recursion, Search, Sorting



Used in:

SRM 210

Used as:

Division I Level One

Writer:

the_one_smiley

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2937

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5856&pm=2937

Problem Statement

    

A computer connected to the internet is identified by an IP address. The most common way of displaying an IP address is the dotted quad method: four eight-bit (0-255 in base ten) numbers separated by periods.

Someone has given you a possible IP address, but the periods have been removed, leaving only a string of digits. Write a class IPConverter with a method possibleAddresses that takes a String ambiguousIP containing the digits and returns a String[] containing all the possible IP addresses that can be formed from those digits by inserting three periods to form a dotted quad. Sort the elements of the return value lexicographically, using their string ordering (the period character precedes all digit characters).

The numbers in each of the four positions can have any integer value between zero and 255, inclusive. However, a number may not have leading zeroes. For example, the digits 1902426 can form 1.90.24.26, 19.0.24.26, 190.2.4.26, and other IP addresses (see Example 0). However, it cannot form 19.02.4.26.

 

Definition

    
Class:IPConverter
Method:possibleAddresses
Parameters:String
Returns:String[]
Method signature:String[] possibleAddresses(String ambiguousIP)
(be sure your method is public)
    
 

Constraints

-ambiguousIP will contain between 0 and 50 characters, inclusive.
-Each character of ambiguousIP will be between '0' and '9', inclusive.
 

Examples

0)
    
"1902426"
Returns: 
{ "1.90.24.26",
 "1.90.242.6",
 "19.0.24.26",
 "19.0.242.6",
 "190.2.4.26",
 "190.2.42.6",
 "190.24.2.6" }
This is the example from the problem statement.
1)
    
"000"
Returns: { }
2)
    
""
Returns: { }
3)
    
"0186290"
Returns: { "0.18.62.90",  "0.186.2.90",  "0.186.29.0" }
4)
    
"11111111"
Returns: 
{ "1.1.111.111",
 "1.11.11.111",
 "1.11.111.11",
 "1.111.1.111",
 "1.111.11.11",
 "1.111.111.1",
 "11.1.11.111",
 "11.1.111.11",
 "11.11.1.111",
 "11.11.11.11",
 "11.11.111.1",
 "11.111.1.11",
 "11.111.11.1",
 "111.1.1.111",
 "111.1.11.11",
 "111.1.111.1",
 "111.11.1.11",
 "111.11.11.1",
 "111.111.1.1" }
5)
    
"3082390871771742784899852251737850570843857369760"
Returns: { }
6)
    
"256255255"
Returns: { "2.56.255.255",  "25.6.255.255",  "25.62.55.255" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TopographicalImage

Graph Theory, Recursion, Sorting



Used in:

SRM 210

Used as:

Division II Level Three

Writer:

the_one_smiley

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2932

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5856&pm=2932

Problem Statement

    

Suppose you are standing at the highest point, called M0, of a mountainous landscape. As you look around, you wonder how many different points you could walk to starting from your lofty position without ever going uphill. The set of these points is called peak P0, and the entire landscape can be divided into peaks according to a similar definition. For i > 0, let Mi be the highest point of the landscape not contained in peaks P0 through Pi - 1, and let peak Pi be the set of points to which there is a path from Mi that never goes uphill (but may remain level) and never touches points already contained in P0 through Pi - 1. The number of peaks in the landscape is the smallest value of n for which all points of the landscape are contained in P0 through Pn - 1.

You have a topographical map of a rectangular landscape, and you are interested in the area of its peaks. Write a class TopographicalImage with a method calcPeakAreas that takes a String[] topoData containing the height of the landscape at each x and y position and returns a int[] with the areas of each peak. The ASCII value of character x of element y of topoData is the height of the landscape at point (x,y). You can walk from a point to each of its vertical, horizontal, and diagonal neighbors. The return value should have a number of elements equal to the number of peaks in the landscape, and element i should be the number of points in Pi. If there is a tie between multiple points for maximum height when choosing Mi, choose the point with the smallest y-coordinate. If there is still a tie between points with the same y-coordinate, choose the point with the smallest x-coordinate.

 

Definition

    
Class:TopographicalImage
Method:calcPeakAreas
Parameters:String[]
Returns:int[]
Method signature:int[] calcPeakAreas(String[] topoData)
(be sure your method is public)
    
 

Notes

-Point Mi is always contained in peak Pi, so the area of a peak is always at least 1.
 

Constraints

-topoData will contain between 1 and 50 elements, inclusive.
-Each element of topoData will contain between 1 and 50 characters, inclusive.
-Each element of topoData will contain the same number of characters.
-Each element of topoData will contain only characters with ASCII value between 33 and 126, inclusive.
 

Examples

0)
    
{
"............",
"....i..i....",
"....i..i....",
".o..i..i..o.",
".o........o.",
"..oooooooo..",
"............"
}
Returns: { 78,  3,  3 }
1)
    
{
"............",
"....i..i....",
"....i..i....",
".S..i..i..Y.",
".M........E.",
"..ILEYSMIL..",
"............"
}
Returns: { 69,  3,  2,  5,  3,  1,  1 }
2)
    
{
"zzzzzzzzzzzzz",
"z...........z",
"z...c.b.c...z",
"z....bab.b..z",
"z...c.b.c...z",
"z...........z",
"zzzzzzzzzzzzz"
}
Returns: { 81,  6,  2,  1,  1 }
3)
    
{"!"}
Returns: { 1 }
4)
    
{
"AAAAAAABBBBCCCDEFGHHIIJIIHGFEDDCCCBBBBBBBBBBAAAAAA",
"AAAAABBBBBCCDDEEFGHIJJJJIIHGFEDDCCCCCCCCCBBBBBAAAA",
"AAAABBBBCCCDDEEFGHIIJJJJJIHGFEDDDDDDDDDCCCCBBBBAAA",
"AAABBBBCCDDEEFFGHHIJJJJJJIHGFEEDDDDDEEDDDDCCBBBBAA",
"AABBBCCDDEEFFGGHHIIJJJJJIHHGFEEEEEEEFFFEEDDCCBBBAA",
"BBBBCCDDEFFGHHHIIIIJJJIIIHGFFEEEEFFGGGGGFEEDCCBBBA",
"BBBCCDEEFGHIIIJJJJIIIIIHHGGFFEEFFGGHHHHHGGFEDCCBBB",
"BBCCDEEGHIJJKKKKJJJIIHHGGFFEEEEFGGHIIJJIIHGFEDCCBB",
"CCCDEEFHIJKLMMMLKKJIHHGGFFEEEEFFGHIJJKKJJIHGFEDCBB",
"CDDEEFHIJLMNNNNMLKJIHGFFEEEDEEFFGIJKKLLLKJIHFEDCCB",
"DDEFFGIJLMNOPPONMLJIHGFEEDDDDEFGHIJKLMMMLKJIGFEDCB",
"EEFFGHIKMNOQQQPONLKIHFEEDDDDDEFGHIKLMMNMMLKIHGEDCC",
"FFGGHIJLMOPQRRQPNMKIGFEDDCCDDEFGHIKLMNNNNMLJIGFEDC",
"GHHHIJKLNOQRRRQPOMKIGFEDDCCDDEFGHIKLMNNNNMLKIHFEDC",
"HIIIJJKLNOPQRRQPNLKIGFEDDCCDDEFGHJKLMNOONNMKJHGFDC",
"IJJJJJKLMOPQQQPONLJHGFEDDDDDEEFGIJKLMNOONNMLJIGFED",
"JJJJJKKLMNOOPPONMKJHGFEDDDDEEFGHIJKLMNNONNMLJIGFED",
"JKKJJJKKLMMNNNNMLJIHFFEEEEEFGGHIJKLMMNNNNMMKJIGFED",
"KKKJJJJJKKLLMLLKJIHGFFEEEFFGHIJKKLMMNNNNNMLKJHGFED",
"JJJJIIIIIJJJKKJJIIHGFFFFFGHIJKLMMNNNNNNMMLKJIHGEDC",
"JJJIIHHHHHHIIIIIHHGGGGGGHIJKLMNOOOOONNMMLKJIHGFEDC",
"IIIHHGGGGGGGGHHHGGGGGGHIIJLMNOPQQQQPONMLKJIHGFEDDC",
"HHHGGFFFFFFFFFGGGGGGHHIJKMNOQRSSSSRQPNMLKIHGFFEDCC",
"GGGFFEEEEEEEEFFFGGGHIJKLMOPRSTUUUTSRPNMKJHGFFEDCCB",
"FFFEEEEDDDDEEEEFGGHIJKLNOQRTUVWWWVTRPNLJIHFEEDCCBB",
"EEEEDDDDDDDDEEEFGHIJKLNOQRTVWXYYXWUSPNLJHGFEDCCBBB",
"DDDDDDDDDDDEEEFFGHIKLNOQRTVWXYZYYWURPMKIGFEDCCBBBB",
"CDDDDDDEEEEEEFFGHIJKMOPRSUWXYZZZXWTROMJHGEDCCBBBBA",
"CCDDDEEEFFFFFGGHHJKLNOQRTVWXYZZYXVTQNLIGFEDCBBBAAA",
"CCDDEFFGGGGHHHHIIJKMNPQSTVWXYYYXVURPMKIGEDCBBBAAAA",
"CDDEFGGHIIIIIIIJJKLMOPQSTUVWWXWVUSQNLJHFECCBBBAAAA",
"CDEFGHIJKKKKKKKKKLMNOPQRSTUVVVUTSQOMJHGEDCBBBAAAAA",
"CDEGHIKLMMMMMMLLLMMNOPQRSSTTTTSRQOMKIGFDCCBBAAAAAA",
"DEFGIKLMNOOOONNMMMNNOPQQRRRRRRQPNMKIHFEDCBBBAAAAAA",
"DEGHJLMOPQQQPPOONNNOOPPPQQQPPONMLKIHFEDCBBBAAAAAAA",
"DEGIKMNPQRRRRQPOOOOOOOPPPOOONMLKJIHFEDCCBBAAAAAAAA",
"DFGIKMOQRSSSRRQPOOOOOOOOONMMLKJIHGFEDCCBBBAAAAAAAA",
"DFGIKMOQRSSSRRQPOOOOONNNMMLKJIIHGFEDCCBBBAAAAAAAAA",
"DEGIJLNPQRRRRQPOONNNNNMMLLKJIHGFEEDCCBBBAAAAAAAAAA",
"DEFHJKMOPQQQQPOONNMMMMLLKJIHGGFEDDCCBBBAAAAAAAAAAA",
"CDFGIJLMNOOOONNMMLLLLLKKJIHGFEEDCCCBBBAAAAAAAAAAAA",
"CDEFGIJKLMMMMMLLKKKKKJJIIHGFEDDCCBBBBAAAAAAAAAAAAA",
"CCDEFGHIJKKKKKJJJIIIIIHHGGFEDDCCBBBBAAAAAAAAAAAAAA",
"BCCDEFGHHIIIIIHHHHHHHGGGFFEDDCCBBBAAAAAAAAAAAAAAAA",
"BBCCDEEFFGGGGGGFFFFFFFFEEDDCCCBBBAAAAAAAAAAAAAAAAA",
"BBBCCDDEEEEEEEEEEEEEEEEDDDCCBBBBAAAAAAAAAAAAAAAAAA",
"ABBBCCCCDDDDDDDDDDDDDDDCCCCBBBBAAAAAAAAAAAAAAAAAAA",
"AABBBBBCCCCCCCCCCCCCCCCCCBBBBBAAAAAAAAAAAAAAAAAAAA",
"AAABBBBBBBBBBBBBBBBBBBBBBBBBAAAAAAAAAAAAAAAAAAAAAA",
"AAAAAABBBBBBBBBBBBBBBBBBBBAAAAAAAAAAAAAAAAAAAAAAAA"
}
Returns: { 1918,  65,  483,  5,  5,  24 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

HierarchicalTree

Graph Theory, Recursion, Sorting, String Parsing



Used in:

SRM 210

Used as:

Division I Level Two

Writer:

the_one_smiley

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2930

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5856&pm=2930

Problem Statement

    

Many systems of information are naturally organized as hierarchical trees. For example, a computer file system has a hierarchical structure of nested directories, and a textbook could be successively divided into chapters, sections, and subsections. In a hierarchical tree, the root node has no parent, and all other nodes are descendants of the root with exactly one parent each. Therefore, even though a node can have any number of children (zero or more), it is possible to describe the structure of a tree by specifying just the parent of each node.

You have a list of node-parent relationships and you want to analyze the structure of the hierarchical tree. All nodes are named with strings of lowercase alphabetical characters, except for the root node which is named ROOT. Write a class HierarchicalTree with a method countDescendants that takes a String[] parentData containing the nodes and their parents and returns a String[] listing the number of descendants of each node. If parentData describes a structure that is not a hierarchical tree, return an empty String[].

The elements of parentData should be concatenated, in order, onto an initially empty string. The resulting string will contain pairs of the form NODE,PARENT separated by exactly one space character. NODE represents the name of a node, and PARENT represents the name of NODE's parent. A name will either consist of all lowercase English characters ('a' to 'z') or be ROOT. The elements of the return value should be formatted "NODE: DESCENDANT_COUNT" (quotes are for clarity) with exactly one space character between the colon and the number of descendants, which should contain no extra leading zeroes. The elements of the return value should be sorted in lexicographical order by NODE. Since ROOT is capitalized, it should always precede the other nodes in the returned array.

 

Definition

    
Class:HierarchicalTree
Method:countDescendants
Parameters:String[]
Returns:String[]
Method signature:String[] countDescendants(String[] parentData)
(be sure your method is public)
    
 

Notes

-The ROOT node always exists.
-The name of a node uniquely identifies it. There cannot be multiple nodes with the same name, even if they have different parents.
-A node does not count as its own descendant.
 

Constraints

-parentData will contain between 0 and 50 elements, inclusive.
-Each element of parentData will contain between 0 and 50 characters, inclusive.
-When the elements of parentData are concatenated, the resulting string will be a list of name pairs with no leading or trailing spaces. Members of a pair will be separated by a single comma, and pairs will be separated by a single space. Names will be lowercase alphabetical English characters ('a' to 'z') or ROOT.
 

Examples

0)
    
{"bin,ROOT tty,dev dev,ROOT passwd,etc etc,ROOT lib",
",ROOT mnt,ROOT proc,ROOT tmp,ROOT usr,ROOT var,RO",
"OT libc,lib screens,tmp kernel,usr log,var tty,de",
"v"}
Returns: 
{ "ROOT: 15",
 "bin: 0",
 "dev: 1",
 "etc: 1",
 "kernel: 0",
 "lib: 1",
 "libc: 0",
 "log: 0",
 "mnt: 0",
 "passwd: 0",
 "proc: 0",
 "screens: 0",
 "tmp: 1",
 "tty: 0",
 "usr: 1",
 "var: 1" }
A node doesn't have to be specified as a child before it is specified as a parent. Also, redundant specifications may exist (tty,dev appears twice).
1)
    
{""}
Returns: { "ROOT: 0" }
2)
    
{"disconnectb,disconnecta cyclea,ROOT intermediatea",
",cyclea cycleb,intermediatea cyclea,cycleb ROOT,r",
"ootparent"}
Returns: { }
There are three things wrong with this tree. First, disconnecta and disconnectb are not descendants of ROOT. Second, cyclea has two parents. Third, rootparent is specified as the parent of ROOT.
3)
    
{"sapiens,homo homo,hominidae hominidae,primates pri",
"mates,mammalia mammalia,chordata chordata,animalia",
" animalia,eukarya eukarya,ROOT ",
"protista,eukarya fungi,eukarya plantae,eukarya ",
"porifera,animalia cnidaria,animalia platyhelminthe",
"s,animalia nematoda,animalia mollusca,animalia ann",
"elida,animalia arthropoda,animalia echinodermata,a",
"nimalia ",
"agnatha,chordata chondrichthyes,chordata osteichth",
"yes,chordata amphibia,chordata reptilia,chordata a",
"ves,chordata ",
"artiodactyla,mammalia carnivora,mammalia cetacea,m",
"ammalia chiroptera,mammalia dermoptera,mammalia hy",
"racoidea,mammalia insectivora,mammalia lagomorpha,",
"mammalia macroscelidea,mammalia notoryctemorphia,m",
"ammalia perissodactyla,mammalia pholidota,mammalia",
" proboscidea,mammalia rodentia,mammalia scandentia",
",mammalia sirenia,mammalia tubulidentata,mammalia ",
"xenarthra,mammalia ",
"lemuridae,primates cheirogaleidae,primates indrida",
"e,primates daubentoniidae,primates galagonidae,pri",
"mates loridae,primates megaladapidae,primates tars",
"iidae,primates cebidae,primates cercopithecidae,pr",
"imates callitrichidae,primates hylobatidae,primate",
"s ",
"gorilla,hominidae pan,hominidae pongo,hominidae ",
"domain,ROOT kingdom,domain phylum,kingdom class,ph",
"ylum order,class family,order genus,family species",
",genus ninja,mammalia"}
Returns: 
{ "ROOT: 67",
 "agnatha: 0",
 "amphibia: 0",
 "animalia: 54",
 "annelida: 0",
 "arthropoda: 0",
 "artiodactyla: 0",
 "aves: 0",
 "callitrichidae: 0",
 "carnivora: 0",
 "cebidae: 0",
 "cercopithecidae: 0",
 "cetacea: 0",
 "cheirogaleidae: 0",
 "chiroptera: 0",
 "chondrichthyes: 0",
 "chordata: 45",
 "class: 4",
 "cnidaria: 0",
 "daubentoniidae: 0",
 "dermoptera: 0",
 "domain: 7",
 "echinodermata: 0",
 "eukarya: 58",
 "family: 2",
 "fungi: 0",
 "galagonidae: 0",
 "genus: 1",
 "gorilla: 0",
 "hominidae: 5",
 "homo: 1",
 "hylobatidae: 0",
 "hyracoidea: 0",
 "indridae: 0",
 "insectivora: 0",
 "kingdom: 6",
 "lagomorpha: 0",
 "lemuridae: 0",
 "loridae: 0",
 "macroscelidea: 0",
 "mammalia: 38",
 "megaladapidae: 0",
 "mollusca: 0",
 "nematoda: 0",
 "ninja: 0",
 "notoryctemorphia: 0",
 "order: 3",
 "osteichthyes: 0",
 "pan: 0",
 "perissodactyla: 0",
 "pholidota: 0",
 "phylum: 5",
 "plantae: 0",
 "platyhelminthes: 0",
 "pongo: 0",
 "porifera: 0",
 "primates: 18",
 "proboscidea: 0",
 "protista: 0",
 "reptilia: 0",
 "rodentia: 0",
 "sapiens: 0",
 "scandentia: 0",
 "sirenia: 0",
 "species: 0",
 "tarsiidae: 0",
 "tubulidentata: 0",
 "xenarthra: 0" }
The phylogeny of living organisms can be represented as a hierarchical tree.
4)
    
{"duke,ROOT arizona,duke maryland,duke michiganst,a",
"rizona usc,duke stanford,maryland temple,michigan",
"st illinois,arizona ucla,duke kentucky,usc cincin",
"nati,stanford georgetown,maryland gonzaga,michiga",
"nst pennst,temple kansas,illinois mississippi,ari",
"zona missouri,duke utahst,ucla bostoncollege,usc ",
"iowa,kentucky stjosephs,stanford kentstate,cincin",
"nati georgiast,maryland hampton,georgetown fresno",
"st,michiganst indianast,gonzaga florida,temple no",
"rthcarolina,pennst charlotte,illinois syracuse,ka",
"nsas notredame,mississippi butler,arizona monmout",
"h,duke georgia,missouri ohiost,utahst hofstra,ucl",
"a oklahomast,usc southernutah,bostoncollege creig",
"hton,iowa holycross,kentucky ncgreensboro,stanfor",
"d georgiatech,stjosephs byu,cincinnati indiana,ke",
"ntstate wisconsin,georgiast georgemason,maryland ",
"arkansas,georgetown iowast,hampton alabamast,mich",
"iganst california,fresnost virginia,gonzaga oklah",
"oma,indianast texas,temple westernky,florida prov",
"idence,pennst princeton,northcarolina northwester",
"nst,illinois tennessee,charlotte hawaii,syracuse ",
"csnorthridge,kansas xavier,notredame iona,mississ",
"ippi wakeforest,butler easternill,arizona winthro",
"p,northwesternst"}
Returns: 
{ "ROOT: 65",
 "alabamast: 0",
 "arizona: 32",
 "arkansas: 0",
 "bostoncollege: 1",
 "butler: 1",
 "byu: 0",
 "california: 0",
 "charlotte: 1",
 "cincinnati: 3",
 "creighton: 0",
 "csnorthridge: 0",
 "duke: 64",
 "easternill: 0",
 "florida: 1",
 "fresnost: 1",
 "georgemason: 0",
 "georgetown: 3",
 "georgia: 0",
 "georgiast: 1",
 "georgiatech: 0",
 "gonzaga: 3",
 "hampton: 1",
 "hawaii: 0",
 "hofstra: 0",
 "holycross: 0",
 "illinois: 8",
 "indiana: 0",
 "indianast: 1",
 "iona: 0",
 "iowa: 1",
 "iowast: 0",
 "kansas: 3",
 "kentstate: 1",
 "kentucky: 3",
 "maryland: 15",
 "michiganst: 15",
 "mississippi: 3",
 "missouri: 1",
 "monmouth: 0",
 "ncgreensboro: 0",
 "northcarolina: 1",
 "northwesternst: 1",
 "notredame: 1",
 "ohiost: 0",
 "oklahoma: 0",
 "oklahomast: 0",
 "pennst: 3",
 "princeton: 0",
 "providence: 0",
 "southernutah: 0",
 "stanford: 7",
 "stjosephs: 1",
 "syracuse: 1",
 "temple: 7",
 "tennessee: 0",
 "texas: 0",
 "ucla: 3",
 "usc: 7",
 "utahst: 1",
 "virginia: 0",
 "wakeforest: 0",
 "westernky: 0",
 "winthrop: 0",
 "wisconsin: 0",
 "xavier: 0" }
The results of single-elimination tournaments can also be expressed as hierarchical trees.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MatchMaking

Simulation, Sorting



Used in:

SRM 203

Used as:

Division I Level One , Division II Level Two

Writer:

Eeyore

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2911

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5849&pm=2911

Problem Statement

    

You are developing the matchmaking component of an online dating site. Prospective members must fill out a questionnaire consisting of binary questions such as Do you prefer to vacation (a) in the mountains or (b) at the seaside? and Would you rather travel (a) by plane or (b) by train?

You are to match up men with women by maximizing the number of answers each couple has in common. A man and a woman have an answer in common whenever they give the same answer to the same question. Conflicts can easily arise due to numerical ties, but you will be able to resolve all such conflicts using the following procedure. Note that there will be equal numbers of men and women, with names being unique in each sex.

Take the woman whose name comes earliest in lexicographic order, and consider the men with whom she has the greatest number of answers in common. Among these men, pick the one whose name comes earliest in lexicographic order. You have found the woman's best match. Remove this couple from the dating pool, and repeat the matching procedure until there are no more singles left.

You are given a String[], namesWomen, containing the names of single women, and another String[], answersWomen, containing their answers. The kth element of answersWomen lists the answers of the woman whose name is the kth element of namesWomen. If there are n questions in the questionnaire, then every element of answersWomen consists of n characters, each of which is either 'a' or 'b'. The answers are always given in the fixed questionnaire order. You are similarly given the String[]s namesMen and answersMen for the single men. Lastly, you are given a String, queryWoman, containing the name of a woman. Return the name of the man to whom she is matched after you have formed all couples according to the above rules.

 

Definition

    
Class:MatchMaking
Method:makeMatch
Parameters:String[], String[], String[], String[], String
Returns:String
Method signature:String makeMatch(String[] namesWomen, String[] answersWomen, String[] namesMen, String[] answersMen, String queryWoman)
(be sure your method is public)
    
 

Notes

-Lexicographic order is like dictionary order, with the difference that case matters. All uppercase letters take precedence over all lowercase letters. Thus, "boolean" comes before "boot"; "boo" comes before "boolean"; "Boot" comes before "boo"; "Zoo" comes before "boo".
 

Constraints

-namesWomen contains between 1 and 50 elements, inclusive
-if namesWomen consists of n elements, then answersWomen, namesMen, and answersMen consist of n elements each
-each element of namesWomen and each element of namesMen is between 1 and 50 characters long, inclusive
-the only characters that may appear in namesMen and namesWomen are 'a' to 'z' and 'A' to 'Z'
-no two elements of namesWomen are alike
-no two elements of namesMen are alike
-the first element of answersWomen is between 1 and 50 characters long, inclusive
-if the first element of answersWomen consists of m characters, then each element of answersWomen and of answersMen is m characters long
-the only characters that may appear in answersWomen and answersMen are 'a' and 'b'
-queryWoman is one of the Strings in namesWomen
 

Examples

0)
    
{"Constance", "Bertha", "Alice"}
{"aaba", "baab", "aaaa"}
{"Chip", "Biff", "Abe"}
{"bbaa", "baaa", "aaab"}
"Bertha"
Returns: "Biff"
Alice has two answers in common with Chip and three answers in common with both Abe and Biff; Abe gets lexicographic preference. Bertha also has two answers in common with Chip and three answers in common with both Abe and Biff. Since Abe has already been matched to Alice, Bertha lands Biff.
1)
    
{"Constance", "Bertha", "Alice"}
{"aaba", "baab", "aaaa"}
{"Chip", "Biff", "Abe"}
{"bbaa", "baaa", "aaab"}
"Constance"
Returns: "Chip"
We are dealing with the same names and answers as before. Constance is the last to go. Although she has two answers in common with Abe and Biff, they are both taken. She ends up with Chip, with whom she has only one answer in common.
2)
    
{"Constance", "Alice", "Bertha", "Delilah", "Emily"}
{"baabaa", "ababab", "aaabbb", "bababa", "baabba"}
{"Ed", "Duff", "Chip", "Abe", "Biff"}
{"aabaab", "babbab", "bbbaaa", "abbbba", "abaaba"}
"Constance"
Returns: "Duff"
3)
    
{"Constance", "Alice", "Bertha", "Delilah", "Emily"}
{"baabaa", "ababab", "aaabbb", "bababa", "baabba"}
{"Ed", "Duff", "Chip", "Abe", "Biff"}
{"aabaab", "babbab", "bbbaaa", "abbbba", "abaaba"}
"Delilah"
Returns: "Chip"
4)
    
{"Constance", "Alice", "Bertha", "Delilah", "Emily"}
{"baabaa", "ababab", "aaabbb", "bababa", "baabba"}
{"Ed", "Duff", "Chip", "Abe", "Biff"}
{"aabaab", "babbab", "bbbaaa", "abbbba", "abaaba"}
"Emily"
Returns: "Ed"
5)
    
{"anne", "Zoe"}
{"a", "a"}
{"bob", "chuck"}
{"a", "a"}
"Zoe"
Returns: "bob"
6)
    
{"F", "M", "S", "h", "q", "g", "r", "N", "U", "x", "H", "P",
 "o", "E", "R", "z", "L", "m", "e", "u", "K", "A", "w", "Q",
 "O", "v", "j", "a", "t", "p", "C", "G", "k", "c", "V", "B",
 "D", "s", "n", "i", "f", "T", "I", "l", "d", "J", "y", "b"}
{"abaabbbb", "bbaabbbb", "aaabaaab", "aabbaaaa", "baabbaab",
 "aaababba", "bbabbbbb", "bbbabbba", "aaabbbba", "aabbbaaa",
 "abbabaaa", "babbabbb", "aaaaabba", "aaaabbaa", "abbbabaa",
 "babababa", "abbaaaaa", "bbababba", "baaaaaba", "baaaaabb",
 "bbbbabba", "ababbaaa", "abbbabab", "baabbbaa", "bbbaabbb",
 "aababbab", "ababbabb", "abbaabba", "baabbabb", "aaabaaab",
 "aabbbaba", "aabaaabb", "abababba", "aabbaaaa", "aabbabaa",
 "bababaaa", "aabaaaab", "bbbbaabb", "baaababb", "abaabbab",
 "aabbbaaa", "baabbaba", "bbabbbaa", "aabbbbaa", "abbbaaab",
 "abababbb", "ababaaba", "bababaaa"}
{"f", "C", "v", "g", "Q", "z", "n", "c", "B", "o", "M", "F",
 "u", "x", "I", "T", "K", "L", "E", "U", "w", "A", "d", "t",
 "e", "R", "D", "s", "p", "q", "m", "r", "H", "j", "J", "V",
 "l", "a", "k", "h", "G", "y", "i", "P", "O", "N", "b", "S"}
{"bbbaabab", "bbabaabb", "ababbbbb", "bbbababb", "baababaa",
 "bbaaabab", "abbabbaa", "bbbabbbb", "aabbabab", "abbababa",
 "aababbbb", "bababaab", "aaababbb", "baabbaba", "abaaaaab",
 "bbaababa", "babaabab", "abbabbba", "ababbbab", "baabbbab",
 "babbaaab", "abbbbaba", "bbabbbba", "baaabaab", "ababbabb",
 "abbbaabb", "bbbbaabb", "bbbaaabb", "baabbaba", "bbabaaab",
 "aabbbaab", "abbbbabb", "bbaaaaba", "bbbababa", "abbaabba",
 "bababbbb", "aabaaabb", "babbabab", "baaaabaa", "ababbaba",
 "aaabaabb", "bbaaabaa", "baaaaabb", "bbaabaab", "bbababab",
 "aabaaaab", "aaaaabab", "aabbaaba"}
"U"
Returns: "x"
7)
    
{"q", "M", "w", "y", "p", "N", "s", "r", "a", "H", "o", "n",
 "F", "m", "l", "b", "D", "j", "C", "u", "f", "I", "g", "L",
 "i", "x", "A", "G", "O", "k", "h", "d", "c", "E", "B", "v",
 "J", "z", "K", "e", "t"}
{"aabbaaabb", "baabababb", "bbaababba", "bbbaaaaaa", "abaaaabaa",
 "bababbbab", "abbaabbaa", "aabababbb", "bababaaaa", "abbababaa",
 "aabbbbbba", "bbabbabab", "babaabbba", "babbabbbb", "baaabbbbb",
 "baaabaaaa", "aaabbaaab", "abbaabbbb", "abbabbbab", "bbaaaabba",
 "babbaaabb", "aabbabbab", "baaababba", "ababaabab", "bbbaabbab",
 "aaaabbabb", "babaaaaaa", "abbbbaaab", "aabaaabba", "bbbaaaaba",
 "bbbbbbaab", "aabbaaabb", "aabaabbab", "aababaaba", "bbabbbbab",
 "abbabaaab", "babaaabbb", "bababbaaa", "aabbaabaa", "baaabbabb",
 "bbbbbbbbb"}
{"m", "k", "n", "q", "L", "E", "M", "l", "w", "x", "g", "e",
 "i", "z", "F", "r", "a", "h", "f", "D", "J", "K", "j", "v",
 "A", "t", "N", "y", "s", "c", "o", "p", "d", "b", "B", "G",
 "O", "I", "u", "C", "H"}
{"bbaaabbba", "bbaaaaaab", "abaaababb", "baaaabbbb", "abbbababa",
 "baaaaaaaa", "aabbbbbab", "aaaaabbba", "baabababb", "babaaabab",
 "baaababaa", "bbbbaabba", "bbaabbabb", "bbaaababb", "abbabbaba",
 "aababaaab", "abbbbbbaa", "aabbaabaa", "bbbaabbba", "abbabbaba",
 "aaabbbaaa", "bbaabaaaa", "aabababbb", "abbbbabab", "baaabbbba",
 "bababbbba", "aababbaab", "bbaabbaab", "bbbaaabbb", "babbbbabb",
 "ababababb", "babaaabab", "bbaaaaaba", "aaaaabaaa", "abbaaabbb",
 "bbbbababb", "baabababb", "bbaabaaaa", "aaababbbb", "abbbbbbba",
 "bbaabbaaa"}
"o"
Returns: "C"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Graduation

Graph Theory



Used in:

SRM 200

Used as:

Division I Level Three

Writer:

antimatter

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2852

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5075&pm=2852

Problem Statement

    

You are a student advisor at TopCoder University (TCU). The graduation requirements at TCU are somewhat complicated. Each requirement states that a student must take some number of classes from some set, and all requirements must be satisfied for a student to graduate. Each class is represented as a single distinct character. For example, one requirement might be "Take any 2 classes of B, C, D, or F." Further complicating the matter is the fact that no class can be used to satisfy more than one requirement. And so students come to you all the time, dazed and confused, because they don't know how close they are to satisfying the requirements so that they can graduate!

Each class is represented as a distinct single character whose ASCII value is between 33 and 126, inclusive, but is also not a numeric character ('0'-'9'). You will be given a String classesTaken, which represents the classes that a given student has taken. You will also be given a String[] requirements, which lists the requirements needed to graduate. Each String in requirements will start with a positive integer, followed by some number of classes. For example, the requirement "Take any 2 classes from B, C, D, or F" would be represented in requirements as "2BCDF".

Your method should return a String representing the classes that the student needs to take in order to graduate, in ASCII order. Classes may not be taken more than once. If there is more than one set that will allow the student to graduate, return the smallest set. If there are multiple smallest sets, return the lexicographically smallest of these. Finally, if there is no set that will enable this student to graduate, return "0".

 

Definition

    
Class:Graduation
Method:moreClasses
Parameters:String, String[]
Returns:String
Method signature:String moreClasses(String classesTaken, String[] requirements)
(be sure your method is public)
    
 

Notes

-Classes may not be taken more than once.
 

Constraints

-classesTaken will be between 0 and 50 characters in length, inclusive.
-each character in classesTaken will be a valid class (ASCII value between 33 to 126 inclusive and not a digit).
-there will be no duplicate classes in classesTaken.
-requirements will contain between 1 and 50 elements, inclusive.
-each element of requirements will contain a positive integer with no leading zeros between 1 and 100, inclusive, followed by some number of valid classes.
-each element of requirements will be between 1 and 50 characters in length, inclusive.
-there will be no duplicate classes in any given element of requirements
 

Examples

0)
    
"A"
{"2ABC","2CDE"}
Returns: "BCD"
The student must take two classes from {A,B,C}, and two from {C,D,E}. He has already taken A.
1)
    
"+/NAMT"
{"3NAMT","2+/","1M"}
Returns: ""
The student has already fulfilled all the requirements - you should congratulate him for his achievement!
2)
    
"A"
{"100%*Klju"}
Returns: "0"
No matter how hard you try, you can't take 100 classes out of 6. TCU had better fix their policies quick.
3)
    
""
{"5ABCDE","1BCDE,"}
Returns: ",ABCDE"
4)
    
"CDH"
{"2AP", "3CDEF", "1CDEFH"}
Returns: "AEP"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DungeonEscape

Graph Theory



Used in:

SRM 198

Used as:

Division I Level Two

Writer:

Rustyoldman

Testers:

brett1479 , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2449

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5073&pm=2449

Problem Statement

    

You are the famous explorer Indiana Jones, or Lara Croft, take your pick. You are exploring the ruins of the dungeons beneath King Lockumup IV the Good's castle in Flatlandia. Of course, the dungeon layout is two-dimensional (like your character), East-West and Up-Down in this case, in a regular grid.

                        Surface
                    | | | | | | | | |
level 0            -R-R-R-R-R-R-R-R-R-
                    | | | | | | | | |
level 1   <- West  -R-R-R-R-R-R-R-R-R- East ->
                    | | | | | | | | |
level 2            -R-R-R-R-R-R-R-R-R-  
                    | | | | | | | | |
                    Depths of Despair

"R" indicates a room. "-" indicates an east-west passageway. "|" indicates an up-down passageway.

Because it is rough going in the passageways between the rooms (there has been no dungeon maintenance for centuries), it is frequently easier to travel through a passageway in a particular direction than in the opposite direction. Each room has four passageways leaving in the directions East (right), West (left), Up, and Down which lead to adjacent rooms (except the Down in the bottom-most rooms, the East in the east-most rooms, and the West in the west-most rooms, which have dead-end passageways due to ancient budget cuts, and Up in the topmost rooms which lead to the surface). The time it takes to travel through a passageway from a given room to the adjacent rooms is given in four String[]s depending on your direction of travel. A digit between 0 and 9 indicates how many time units (in the local system of decimillifortnights, dmfs) are taken to leave the room in that direction and travel through the passageway to the adjacent room. An 'x' character indicates that the travel in that direction is too difficult and can not be done. The dead end passageways (at the edges of the dungeon) have time values, or 'x', specified (because they were in the original plans for the dungeon and we have an old map), but we can not actually travel through these passageways in this problem. The dungeon does *not* wrap in any direction (you are probably thinking of the castle of Queen Mobius the One Sided, the former stripper).

In other words, if you are in room (i,j), where i is the up-down level and j is your easting (ie. how far east you are) coordinate, then

  • up[i][j] tells how many dmfs it takes to get to (i-1,j).
  • down[i][j] tells how many dmfs it takes to get to (i+1,j).
  • east[i][j] tells how many dmfs it takes to get to (i,j+1).
  • west[i][j] tells how many dmfs it takes to get to (i,j-1).

If it is obvious to you how these four directional time value arrays map to a directed graph of the dungeon, then skip this next section of the problem description, which goes into detail, and continue reading below for more of the important problem description information.

  • For example if given the inputs up and west (shown below)

    up = {"123",      west = {"222",
          "111",              "131",
          "121"}              "444"}
    
    You would have the following time values for each passageway while going up or west.
                       Surface
                        1 2 3 
    level 0            2R2R2R-      Up and West going
                        1 1 1       Passageway times
    level 1      West  1R3R1R- East 
                        1 2 1
    level 2            4R4R4R-      
                        | | |
                  Depths of Despair
    

    The dead-end passageways on the far west with times {2, 1, 4} are useless and can be ignored.



    Similarly if you have the inputs down and east (shown below)

    down = {"987",      east = {"222",
            "111",              "3x3",
            "121"}              "111"}
    
    You would have the following time values for each passageway while going down or east.
                       Surface
                        | | |
    level 0            -R2R2R2     Down and East going
                        9 8 7      Passageway times
    level 1      West  -R3RxR3 East 
                        1 1 1
    level 2            -R1R1R1
                        1 2 1 
                   Depths of Despair
    

    The dead-end passageways on the far east with times {2, 3, 1} and the very bottom with times {1, 2, 1} are also useless to you and can be ignored.

We are back from the boring details, here is some more important information.

Unfortunately for you, Dr. Jones or Dr. Croft, you have just triggered an ancient trap, and the dungeon is beginning to to fill with water. First the lowest level fills with water. If the East-West width of the dungeon is n rooms, then each level of the dungeon takes n decimillifortnights to fill. Once full of water, the rooms on that level are no longer accessible. While partly full of water, they are still fully accessible. Time starts at time = 0, at time = n the lowest level becomes inaccessible, at time = 2n the second lowest level becomes inaccessible, etc. So if you are in, or pass through, a room on the lowest level at time >= n, you are dead.

For simplicity, we will only consider if the room is completely filled with water when you enter. So if you leave a nearly filled room, going up through a slow passageway, and arrive somewhat later in a now nearly filled room one level up, this is ok. We will ignore the physics which would lead us to think the passageway would fill with water before the room above it. Only check for drowning when you enter the room. Also the surface (above level 0) never fills with water (we run out of water before then), so you can not drown on the surface.

Your goal is to get to the surface as fast as possible. You start at the location (startLevel, startEasting). "Easting" is how far east you are in the local coordinate system. Rooms have Easting coordinates between 0 and n-1 inclusive, where n is the number of rooms on each level. Return the number of time units (decimillifortnights) it takes to escape, or -1 if escape is impossible.

For example:

up = {"0x4",  down = {"0x9",   east = {"1x9",   west = {"0x9",
      "0x3",          "009",           "0x9",           "0x0",
      "0x3"}          "0x9"}           "009"}           "009"}
startLevel = 2, startEasting = 2

We start in the lower right corner. If water were not an issue, we could reach each of the various rooms with various paths, and the earliest possible times in which we could reach each room are shown below. If we go straight up, the passageways take 3, 3 and 4 dmfs reaching the surface in 10 dmfs. We could also follow the path: up (3 dmfs), west (0 dmfs), down (0 dmfs), west (0 dmfs), up (0 dmfs), up (0 dmfs), and up (0 dmfs) reaching the surface in 3 dmfs. The diagram below shows the minimum time in which we could first get to each room (if water were not an issue), and the passageways used are shown with '|' for up-down, and '-' for east-west.

      3  10      - surface
      |   |  -------------
      3-4 6      - level 0
      |   |
      3 3-3      - level 1
      | | |
      3-3 0      - level 2

But since level 2 fills with water at time 3, we can not move from (1,1) down to (2,1) at time = 3 dmfs. The actual rooms we can reach, considering flooding, are shown below, where 'w' represents a room which is full of water when we first could move into it, and 'x' represents a room we can never reach:

         10      - surface
          |   ------------
      x w-6      - level 0
          |
      x 3-3      - level 1
        | |
      x w 0      - level 2

In this example we can reach the surface in 10 dmfs by going straight up, and this is the minimum, so return 10.

 

Definition

    
Class:DungeonEscape
Method:exitTime
Parameters:String[], String[], String[], String[], int, int
Returns:int
Method signature:int exitTime(String[] up, String[] down, String[] east, String[] west, int startLevel, int startEasting)
(be sure your method is public)
    
 

Constraints

-up, down, east and west have the same constraints, only up is described.
-up will contain between 1 and 50 elements inclusive.
-each element of up will contain between 1 and 50 characters inclusive.
-each character in each element of up will be a digit between '0' and '9' inclusive or 'x'.
-up, down, east and west will all have exactly the same number of elements in each.
-All elements of up, down, east and west will contain the same number of characters.
-startLevel will be between 0 and (the number of elements in up) - 1 inclusive.
-startEasting will be between 0 and (the number of characters in up[0]) - 1 inclusive.
 

Examples

0)
    
{"0x4",
 "0x3",
 "0x3"}
{"0x9",
 "009",
 "0x9"}
{"0x9",
 "1x9",
 "009"}
{"0x9",
 "0x0",
 "009"}
2
2
Returns: 10
The example from above.
1)
    
{"xxxxxxxxx1",
 "1xxxxxxxxx",
 "xxxxxxxxx1"}
{"xxxxxxxxxx",
 "xxxxxxxxxx",
 "xxxxxxxxxx"}
{"1111111111",
 "xxxxxxxxxx",
 "1111111111"}
{"xxxxxxxxxx",
 "1111111111",
 "xxxxxxxxxx"}
2
0
Returns: 30
Only one serpentine path out, just avoiding the water.
2)
    
{"xxxxxxxxx1",
 "xxxx999991",
 "x999999991"}
{"1111111111",
 "1111111111",
 "1111111111"}
{"1111122242",
 "2222222241",
 "2111111111"}
{"xxxxxxxxx1",
 "1111111111",
 "xxxxxxxxx1"}
2
0
Returns: -1
No way out that is fast enough, glub, glub...
3)
    
{"1x2x3x4x5x6x7x8x9",
 "00000000000000000",
 "98765432223456789",
 "12345678987654321"}
{"00000000000000000",
 "00000000000000000",
 "00000000000000000",
 "00000000000000000"}
{"xxxxxxxxxxxxxxxxx",
 "xxxxxxxxxxxxxxxxx",
 "22222222222222222",
 "33333333333333333"}
{"xxxxxxxxxxxxxxxxx",
 "xxxxxxxxxxxxxxxxx",
 "22222222222222222",
 "33333333333333333"}
3
12
Returns: 17

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

IslandFerries

Graph Theory



Used in:

SRM 194

Used as:

Division I Level Three

Writer:

legakis

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2437

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5069&pm=2437

Problem Statement

    

You are a traveler in a chain of tropical islands in the South Pacific. Transportation between these islands is provided by competing ferry services. One-way tickets for the ferries can be purchased on each of the islands. The tickets are only accepted by the ferry service for which the ticket was purchased. Each ticket entitles you to ride any single leg offered by that ferry service, where a leg is a trip between any two islands.

Ticket prices vary from island to island, and are published daily in the local newspaper. Armed with the current prices, you wish to decide which island to visit next. Your task is to determine for each island the cheapest path to journey from your current location to that island. You are not concerned with the number of ferries you must ride, only with the cost of the tickets required to make each journey.

Anti-competitive regulations prohibit you from carrying more than one ticket for the same ferry service, and from carrying more than three tickets total. Thus, after stepping off a ferry onto an island, you will have zero, one, or two tickets in your possession, and any tickets you are carrying will not be for the ferry you just rode. You begin with no tickets in your possession, so the first step of any journey must be to purchase one, two, or three tickets on the initial island (island 0).

The available legs will be given as a String[] legs, with each element giving the legs offered by a particular ferry service. The size of legs gives you the number of ferry services. Each element of legs will be formatted as a list of "<island1>-<island2>" (representing a one-way leg from <island1> to <island2>), each separated by a single space.

The prices of ferry tickets sold on each island is given as a String[] prices, with each element giving the prices for tickets on a particular island. The size of prices gives you the number of islands. Each element of prices will be a space-separated list of integers, corresponding to the ticket prices for ferries in the same order they are given in legs.

There will be up to 40 islands and 10 ferry services. Given the list of legs offered by each ferry service and the prices of tickets on each island, for each island compute the cost of traveling there from your initial island (island 0), and return the costs as a int[]. The size of your returned int[] should be one less than the number of islands. If a given island is unreachable, return -1 for the cost to that island.

 

Definition

    
Class:IslandFerries
Method:costs
Parameters:String[], String[]
Returns:int[]
Method signature:int[] costs(String[] legs, String[] prices)
(be sure your method is public)
    
 

Notes

-There is not necessarily a route to all islands.
-The cheapest route may including visiting an island more than once (see example 2 below).
 

Constraints

-legs will contain between 1 and 10 elements, inclusive. The size of legs gives you F, the number of ferry services.
-prices will contain between 2 and 40 elements, inclusive. The size of prices gives you I, the number of islands.
-Each element of legs will contain between 1 and 50 characters, inclusive.
-Each element of prices will contain between 1 and 50 characters, inclusive.
-Each <island> in legs will be an integer between 0 and I-1, inclusive.
-Each element of prices will contain F integers between 1 and 1000, inclusive.
-There will be no duplicates within a given element of legs.
-The jth element in the list of prices[i] gives the price of a ticket for ferry service j sold on island i.
-No integers will have leading zeros.
 

Examples

0)
    
{ "0-1 0-3", "0-2" }
{ "5 7", "1000 1000", "1000 1000", "1000 1000" }
Returns: { 5,  7,  5 }
You need an A ticket (cost of 5) to get to islands 1 and 3, and a B ticket (cost of 7) to get to island 2.
1)
    
{ "0-1 1-2 2-3", "0-1 2-3" }
{ "1 10", "20 25", "50 50", "1000 1000", "1000 1000" }
Returns: { 1,  11,  31,  -1 }

There are 5 islands and 2 ferry services. Referring to the ferry services as A and B, the cheapest way to get to island 1 is to purchase an A ticket on island 0 for a cost of 1 and take the A ferry to island 1.

The cheapest way to get to island 2 is to purchase A and B tickets on island 0 for a total cost of 11. Use the B ticket to get to island 1 and the A ticket to get to island 2.

The cheapest way to get to island 3 is to purchase A and B tickets on island 0 (cost of 11), use the A ticket to get to island 1, purchase another A ticket on island 1 (cost of 20), use it to get to island 2, and then use the B ticket to get to island 3. The total cost is 31.

There is no path to island 4.

2)
    
{ "0-1", "1-0", "0-2", "2-3" }
{ "1 1 1000 1000", "1000 1000 10 100", "1000 1000 1000 1000", "1000 1000 1000 1000" }
Returns: { 1,  12,  112 }
The cheapest way to get to island 3 is to purchase A and B tickets on island 0, take the A ferry to island 1, purchase C and D tickets on island 1, take the B ferry back to island 0, then the C ferry to island 2, and then the D ferry to island 3.
3)
    
{ "1-0" }
{ "793", "350" }
Returns: { -1 }
Legs are directed.
4)
    
{"8-18 4-11 15-5 7-12 11-8 0-15 15-2 3-11 4-18 2-3",
 "16-2 18-3 15-18 11-19 18-2 18-7 19-17 3-15 12-19",
 "2-17 0-12 1-2 14-12 6-2 4-2 11-5 4-11 11-6 17-16",
 "0-18 13-18 16-0 3-7 14-12 3-1 19-18 3-19 10-3 8-15",
 "18-19 3-16 13-6 0-19 12-14 5-17 1-12 7-13 9-14 1-2",
 "14-5 17-9 2-10 16-13 11-15 10-17 14-10 0-14 2-13",
 "4-5 0-17 6-9 17-7 12-6 5-6 6-18 10-18 0-2 13-0 8-4",
 "3-12 4-11 10-17 13-12 3-0 3-7 13-0 9-15 10-9 0-10" }
{"592 219 88 529 324 86 503 610",
 "2 94 8 600 34 95 6 494",
 "638 301 10 246 290 97 85 74",
 "118 8 939 393 450 79 317 99",
 "99 806 698 740 2 26 525 818",
 "95 9 615 972 23 23 5 666",
 "6 448 440 710 83 4 419 496",
 "4 47 182 4 185 70 718 770",
 "3 321 6 855 968 65 10 6",
 "173 224 300 3 79 2 707 49",
 "21 10 7 10 4 9 5 8",
 "6 600 4 724 7 1 960 247",
 "83 16 901 50 437 780 658 2",
 "763 923 125 576 45 423 3 1",
 "7 324 391 898 8 59 281 973",
 "9 44 49 364 78 744 43 5",
 "10 62 75 418 216 90 32 919",
 "764 534 778 605 80 647 821 74",
 "65 449 102 867 421 94 6 7",
 "67 155 362 789 189 316 107 595" }
Returns: 
{ 170,  160,  155,  173,  145,  150,  158,  168,  153,  145,  162,  88,  162,  86,  163,  159,  153,  150,  104 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Paths

Graph Theory



Used in:

SRM 197

Used as:

Division I Level Two

Writer:

ValD

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2431

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5072&pm=2431

Problem Statement

    Being second best usually warrants respect and some degree of popularity. Unfortunately, sometimes being second is worse than being last. This phenomenon can be seen in graph theory path-finding algorithms. No one ever seems to pay attention to second best paths! This is unfair and it leaves many almost optimal paths unseen. You wish to change all this by writing an algorithm that detects the second shortest path length in a directed graph, which is not equal to the optimal shortest path length. For the purpose of this problem, a path does not need to have distinct nodes and the length of a path is the sum of all edge weights from the starting node to the ending node.

Write a class Paths that contains the method secondBest, which takes a String[] graph, int from and int to and returns the length of the second shortest path from the node from to the node to.  graph will contain digits that represent the weights of edges or 'X', which means there is no edge at all.  The jth character of the ith element in graph represents the weight of the edge from node i to node j (i and j are zero-indexed).  If no second best path exists, return -1.
 

Definition

    
Class:Paths
Method:secondBest
Parameters:String[], int, int
Returns:int
Method signature:int secondBest(String[] graph, int from, int to)
(be sure your method is public)
    
 

Notes

-The weight of an edge from node j to node i need not be the same as the weight of an edge from node i to node j.
-Nodes may have an edge pointing to themselves with non-zero weights.
 

Constraints

-graph will contain between 1 and 50 elements, inclusive.
-Each element of graph will contain the same number of characters as the number of elements in graph.
-Each element of graph may contain only digits or 'X'.
-from will be between 0 and the number of elements in graph-1, inclusive.
-to will be between 0 and the number of elements in graph-1, inclusive.
 

Examples

0)
    
{"01111",
 "10111",
 "11011",
 "11101",
 "11110"}
0
0
Returns: 2
In this case, the best path may be no path at all or any number of moves from node 0 back to itself. In either case, the best path is 0. The second best path has a length of 2 and can be achieved by moving from node 0 to any other node, and then back to node 0.
1)
    
{"1"}
0
0
Returns: 1
Since the starting node is the ending node, the best path is 0. The second best path is to move once from node 0 back to itself.
2)
    
{"X1119",
 "1X119",
 "11X19",
 "111X1",
 "9111X"}
0
4
Returns: 3
3)
    
{"X1110",
 "1X111",
 "11111",
 "111X1",
 "0111X"}
0
4
Returns: 2
4)
    
{"X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "XX9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X9X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X99X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X9999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X99999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X9999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X99999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X9999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X99999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X999999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X9999999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X99999999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X999999999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X9999999999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X99999999999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X999999999999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X9999999999999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X99999999999999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X999999999999999999999X9XXXXXXXXXXXXXXXXXXXXXXXXXX",
 "X9999999999999999999999X9XXXXXXXXXXXXXXXXXXXXXXXXX",
 "X99999999999999999999999X9XXXXXXXXXXXXXXXXXXXXXXXX",
 "X999999999999999999999999X9XXXXXXXXXXXXXXXXXXXXXXX",
 "X9999999999999999999999999X9XXXXXXXXXXXXXXXXXXXXXX",
 "X99999999999999999999999999X9XXXXXXXXXXXXXXXXXXXXX",
 "X999999999999999999999999999X9XXXXXXXXXXXXXXXXXXXX",
 "X9999999999999999999999999999X9XXXXXXXXXXXXXXXXXXX",
 "X99999999999999999999999999999X9XXXXXXXXXXXXXXXXXX",
 "X999999999999999999999999999999X9XXXXXXXXXXXXXXXXX",
 "X9999999999999999999999999999999X9XXXXXXXXXXXXXXXX",
 "X99999999999999999999999999999999X9XXXXXXXXXXXXXXX",
 "X999999999999999999999999999999999X9XXXXXXXXXXXXXX",
 "X9999999999999999999999999999999999X9XXXXXXXXXXXXX",
 "X99999999999999999999999999999999999X9XXXXXXXXXXXX",
 "X999999999999999999999999999999999999X9XXXXXXXXXXX",
 "X9999999999999999999999999999999999999X9XXXXXXXXXX",
 "X99999999999999999999999999999999999999X9XXXXXXXXX",
 "X999999999999999999999999999999999999999X9XXXXXXXX",
 "X9999999999999999999999999999999999999999X9XXXXXXX",
 "X99999999999999999999999999999999999999999X9XXXXXX",
 "X999999999999999999999999999999999999999999X9XXXXX",
 "X9999999999999999999999999999999999999999999X9XXXX",
 "X99999999999999999999999999999999999999999999X9XXX",
 "X999999999999999999999999999999999999999999999X9XX",
 "X9999999999999999999999999999999999999999999999X9X",
 "X99999999999999999999999999999999999999999999999X9",
 "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"}
0
49
Returns: 459
5)
    
{"X"}
0
0
Returns: -1
A second best path does not exist in this graph.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WaterBot

Graph Theory



Used in:

SRM 197

Used as:

Division I Level Three

Writer:

ValD

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2428

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5072&pm=2428

Problem Statement

    Every spring, your grandmother plants a garden. Since she is in her later years, she often needs help with watering the plants. Of course, you always offer a helping hand but you also have a more permanent solution. You call your invention "I can't believe it works!", and it is about to bring a revolution to the garden-watering industry. Your creation is a robot that will water the garden, taking the least time possible.

Your job is to implement part of the software that will guide the robot.  The robot may only move and see in the four cardinal directions: North, East, West or South.  The garden will be represented by the String[] garden, which consists of digits, dots, a single 'R' and a single 'W' (quotes for clarity).  Each digit will represent how many units of  water a plant in that location needs.  The character '.' marks an empty location, 'R' marks the robot's current location and 'W' marks the location of a well (quotes for clarity).  During the robot's travels, it may not step on any plants (that would only upset your grandmother) or the well (that would really make you angry).  

Given garden and carryLimit, calculate and return the minimum amount of time needed to water all plants if the robot may only carry at most carryLimit units of water at any time.  It takes n time units to water a plant that needs n units of water.  In addition, m time units are needed to get m units of water from the well and each step in any direction takes 1 unit of time.  The robot can change the direction in which it is facing instantly, taking zero time units.  The robot may only water a plant if it is directly next to it; the same requirement must be met when taking water from the well.  Finally, the robot may water only one plant at a time.  If it is impossible to water all plants, return -1.
 

Definition

    
Class:WaterBot
Method:minTime
Parameters:String[], int
Returns:int
Method signature:int minTime(String[] garden, int carryLimit)
(be sure your method is public)
    
 

Notes

-Initially, the robot is holding zero units of water.
-The robot may not step out of the garden at any time.
 

Constraints

-garden will contain between 1 and 50 elements, inclusive.
-Each element in garden will contain between 1 and 50 characters, inclusive.
-All elements in garden will be of the same size.
-Each element in garden may only contain the following characters: 'W', 'R', '.', '1', '2', '3', '4', '5' (quotes for clarity).
-garden will contain exactly one occurrence of 'R' and 'W'.
-garden will contain between 0 and 4 digits, inclusive.
-carryLimit will be between 1 and 5, inclusive.
 

Examples

0)
    
{"5....",
 ".....",
 ".....",
 ".....",
 "...RW"}
5
Returns: 16
The robot begins its journey next to the well. It takes 5 units of time to collect 5 units of water. Then, it takes 6 units of time to move to the only plant that needs watering. At last, the robot will water the plant for 5 units of time. The total time required is 16 units.
1)
    
{"3.2..",
 ".....",
 ".....",
 "....R",
 "....W"}
5
Returns: 16
Once again, the robot is next to the well. The most efficient schedule is to collect 5 units of water, then water both plants without returning to the well.
2)
    
{".5555",
 ".....",
 ".....",
 "....R",
 "....W"}
3
Returns: 85
3)
    
{"R.....55",
 "......55",
 "........",
 "........",
 "........",
 ".......W"}
2
Returns: -1
The robot cannot reach the top-right plant without stepping on at least one other plant.
4)
    
{"R.......",
 "........",
 "....5...",
 "...5W5..",
 "....5...",
 "........"}
4
Returns: -1
The robot cannot get any water from the well.
5)
    
{".1",
 ".2",
 ".3",
 ".4",
 "R.",
 "W."}
5
Returns: 28
6)
    
{"R....",
 ".....",
 ".....",
 ".....",
 "....W"}
5
Returns: 0
There are no plants to water here.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

EigenVector

Brute Force, Math



Used in:

SRM 192

Used as:

Division I Level Two , Division II Level Three

Writer:

Rustyoldman

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2423

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4780&pm=2423

Problem Statement

    

A matrix is a rectangular (two-dimensional) array of numbers. A vector is a linear sequence of numbers, a one dimensional array. There are row vectors and column vectors. We use only column vectors in this problem. How to multiply a matrix by a column vector (vector on the right) to yield another column vector is described in the notes section.

A right eigenvector, X, of a square matrix, A, is a (nonzero) column vector that satisfies AX=kX, where k is a nonzero scalar constant called an eigenvalue (usually represented by lambda). In other words, multiplying the matrix by the eigenvector yields a vector which is proportional to the eigenvector. For the vectors to be proportional by the factor k, each element of the resulting vector is k times the corresponding element of X, k*X[i].

Given a matrix, find the smallest right eigenvector of that matrix where each element of the eigenvector is an integer. Smallest is defined by the L0 norm, which is the sum of the absolute values of the elements of the vector. The first nonzero element of the eigenvector should be positive (if it is not positive, multiply all the elements by -1). If there are equally small integer eigenvectors, return the lexicographically first eigenvector. A vector v1 comes before v2 lexicographically if v1 has a smaller element in the first position for which the two vectors differ.

To simplify this problem, the input matrix, A, will be at most 5 by 5 and will always have an integer eigenvector with L0 norm between 1 and 9 inclusive.

Some valid vectors (L0 = 5, in lexicographic order):

{0,0,0,5}

{0,0,2,-3}

{1,0,-2,2}

{1,0,1,3}

Some invalid vectors:

{0,0,0} vector must be nonzero

{0,0,-1} first nonzero element must be positive

{0,-1,3} first nonzero element must be positive

{-1,2,3} first nonzero element must be positive

For example:

{"1 0 0 0 0",
 "0 1 0 0 0",
 "0 0 1 0 0",
 "0 0 0 1 0",
 "0 0 0 0 1"}

The identity matrix, I, is unusual in terms of eigenvalues and eigenvectors. All the eigenvalues are 1, and every nonzero vector is an eigenvector. The first one in our ordering is {0,0,0,0,1}.

 

Definition

    
Class:EigenVector
Method:findEigenVector
Parameters:String[]
Returns:int[]
Method signature:int[] findEigenVector(String[] A)
(be sure your method is public)
    
 

Notes

-To calculate matrix-column vector multiplication, AX = Y, where A is an n by n matrix, and X and Y are length n column vectors, use something like: for(i) { Y[i] = 0 ; for(j) { Y[i] = Y[i] + A[i,j] * X[j] ; } }
 

Constraints

-A will be the string representation of an n by n integer matrix where n is between 2 and 5 inclusive. Each element of A represents a row of the matrix with n integer elements in each row.
-A will contain exactly n elements (rows).
-Each element of A will contain exactly n integers (characters between '0' and '9' inclusive, optionally preceded by a minus sign '-'), each separated by a single space.
-There will be no leading or trailing spaces in each element of A. For example: "10 2 0 -4" (quotes for clarity)
-Each of the integers in A will be between -1000 and 1000 inclusive, with no leading zeros.
-The matrix A will have at least one integer right eigenvector having an L0 norm between 1 and 9 inclusive.
 

Examples

0)
    
{"1 0 0 0 0",
 "0 1 0 0 0",
 "0 0 1 0 0",
 "0 0 0 1 0",
 "0 0 0 0 1"}
Returns: { 0,  0,  0,  0,  1 }
The example from above, the identity matrix.
1)
    
{"100 0 0 0",
 "0 200 0 0",
 "0 0 333 0",
 "0 0 0 42"}
Returns: { 0,  0,  0,  1 }
All diagonal matrices (including the identity matrix) will have the same answer: n-1 zeros followed by a one.
2)
    
{"10 -10 -10 10",
 "20 40 -10 -10",
 "10 -10 10 20",
 "10 10 20 5"}
Returns: { 1,  -5,  2,  0 }
3)
    
{"30 20","87 2"}
Returns: { 2,  3 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LumberjackHack

Graph Theory, Search, String Parsing



Used in:

SRM 186

Used as:

Division II Level Three

Writer:

Eeyore

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2410

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4750&pm=2410

Problem Statement

    

If you've driven much on North American highways, especially west of the prairies, you're familiar with the sight of trucks hauling great stacks of logs. In the old days, before internal combustion was a going concern, logs were transported at a more sedate pace by floating them down a river. This was all very picturesque until the logs jammed together so tightly that no movement was possible. Then they had to send someone out on the river to loosen up the works with dynamite. Skipping nimbly from log to log, a lumberjack would find the crux of the logjam and set an explosive charge. After lighting the fuse, he had to skip quickly back to shore. The lumberjack was prepared to plunge briefly into the river as a shortcut, but he really didn't like to get wet. The main thing was to get away quickly.

You are given a String[] describing a stretch of river in which the character '|' stands for a log, '.' stands for water, and '+' is where the lumberjack is standing on a log. The lumberjack can reach safety by stepping up, down, left, or right between adjacent logs until he reaches the far left or far right, at which point he is immediately safe from the blast. (The "far left" is the first character in each String, and the "far right" is the last character in each String.) Stepping up or down onto a log takes him one second, while stepping left or right onto a log takes two seconds. The lumberjack may step on no more than one square of water in his entire trip, at a cost of three seconds instead of the usual one or two. Return the minimal number of seconds it will take the lumberjack to reach safety, or -1 if he cannot do so.

 

Definition

    
Class:LumberjackHack
Method:timeToShore
Parameters:String[]
Returns:int
Method signature:int timeToShore(String[] riverMap)
(be sure your method is public)
    
 

Constraints

-riverMap contains between 1 and 50 elements, inclusive
-the first element of riverMap is between 3 and 50 characters long
-every element of riverMap has the same length as the first element of riverMap
-for every element of riverMap, each character must be '|', '.', or '+'
-riverMap contains exactly one occurrence of the character '+'
 

Examples

0)
    
{".+.",
 "||."}
Returns: 3
The lumberjack can reach safety in 1+2 = 3 seconds by stepping down and to the left.
1)
    
{"..+",
 "||."}
Returns: 0
The lumberjack is already safe at the right edge.
2)
    
{"....|||",
 "....|..",
 "...||..",
 "||.+...",
 "...|...",
 "...||||"}
Returns: 7
The lumberjack could reach the upper right corner in 1+2+1+1+2+2 = 9 seconds or the lower right in 1+1+2+2+2 = 8 seconds, but his best choice is to reach the left border in 3+2+2 = 7 seconds.
3)
    
{"||.|....",
 "........",
 ".|.+|..|",
 "...|....",
 "|..|.|.|"}
Returns: -1
The lumberjack had better not light that fuse.
4)
    
{".........|.|.|.|.|..||...||.|..|.||...|.|.|||...||",
 ".||.||...||..|||.....|.||||...|.|.|.|.|..|...|.|||",
 "||.|.|..||.||....|.....|.||.|||||.|.|.||.|||||.|..",
 "|.....|.|.||||.||..|.|..|..|.|||||.....||.|.||....",
 "..|..||...||.|.......|||+||.||||....||||.....|..||",
 "...||..||||.|......||..|.|||||.|.|||||.||..|||...|",
 "|||...|..|..|.|||.||.|..|...||.|||..|..||.|.||....",
 "|..|||||||||.||.....|..|.|.|||||...||...|.|.|||||.",
 ".|..||...|||............|.|..|||.||.|||.||..||.|||",
 ".|.|||...||..|..|...||.||..|..|||||.|.|...||..||.|",
 "||||.|||.|..||||..|..||...|..||.|.||||...|...|.|..",
 ".||..||...|.....|||.|||||..||......|.||.||.|..||..",
 "|.|||....|||||.|..|..|.|||..|.||.||.|.|.|.|..||...",
 ".||.||||||...||||||..||....|..||.|||..||...|.|||||",
 ".||||.|....|...|.||..||..|||.|||||....|...||.|.||.",
 ".|...|..||....||...|.||||.....||||.||.|||||||..|||",
 ".||||...|...|..||...|...|...|.|..|.|.|..|..|||.||.",
 ".|.|||..||||||||........|||||||||.|.|........|||||",
 ".....|...||.||...|||...||||..|||...||....||..||.||",
 "||...||..||.||...||...||||..|.|..|...|||..||..|||.",
 "|..||||.||..|...|....||||||...|||.|.|||||..|||...|",
 ".....|||..||.|||.....||..||||...|||||.||.|.||..|||",
 "|..|.||..|..||..||..|...|..|.||..||||..|...||..|..",
 "||.|..|.|||||...|...|.|..|||||...|.......|.||.||||",
 ".|.....|.|||||.....|||...|..|||||...|.||..||.|||.|",
 ".|...||....|||...|||.||.|.|......|........|.||||||",
 "..|.|.|.|||||..|||..|.........|...|.|.|...||.....|",
 ".|.|.|.|..|.|||||||||||.|.|||....|||||...|.||||.|.",
 "|.|||....|.||||..||......|..|||||.....||.|..||..|.",
 "||.||.|||.|......|..|.|...|..||.|||..||.....|.|..|",
 ".||||..|.|.||||.|||.||.||.....|....|....||...|..||",
 ".....|||...||.||.||....|.||..||....|....|||||.|..|",
 "|.|.|||||...|.||..|..|..|.|..|.|........||..|.|.||",
 "....|..|.|..|.||||||....||||.|.||||||.|.|.|.......",
 "||||....|..|...||..||||||||...|.|||||.|.|||.|...||",
 "|...|.|..|..|..|....|..||..|||....||..||..|..|..|.",
 "|||||....|.||.|..|.||..|||..|.|.|..||.|...|.|..||.",
 "..|.|||.|.||..|...|||.|..|||..||...||...||||.....|",
 "..||||.|.|.....|||..||||..|.||||..|..|||.....||.||",
 "|..|||||....|........|.||||.||..||||.|....|||||||.",
 ".|...||.|.||..|.|....|.||..|.|....|.|.||.||.||.|..",
 ".|..|..|.||||.||||....|||.....|.|...|.|...|...||..",
 "|..|||..|.||.|||..||.....|.|..|.|.|...|.....|.....",
 "||..||.|...|.||...|..|..||.|||.||.|.||...|....|||.",
 ".|....|.|||.|..|||..|.....|.||.||...|...||.......|",
 ".||..|||.|.|....|||...|..|.||.||.|.|...|||||.|.|.|",
 "|.|.||.||.|.|.||.|||.||....||.|||||.||.|.|||......",
 "|...|||...|.||||....|.||.||.|.........|..||.|..||.",
 ".|.....|.|.|....||.||...|||.|..||...||.|||.||.|.|.",
 "||.||.|||.|||..||......|......||..||||.|..||.||||."}
Returns: 63
5)
    
{".+."}
Returns: 3
6)
    
{"..+.."}
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SimpleIO

Graph Theory



Used in:

SRM 195

Used as:

Division I Level Two

Writer:

schveiguy

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2383

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5070&pm=2383

Problem Statement

    

Consider a simple Input/Output system. The system input consists of a button that you can press, while the system output consists of an audible beep. The system logic consists of a state machine that transitions from one state to the next every time the button is pressed. At the last state, the machine transitions to the first state when the button is pressed. On some state transitions, the audible beep is sounded, and on others it is not. The pattern of beeps mapped to states is known ahead of time.

You are given a String pattern of beeps for state transitions. The i-th character of pattern (0-based index) will be a 'B' if there is a beep when state i is entered, and will be a 'N' if there is no beep. You are also given an int targetState to achieve, but not the starting state. Return the worst case scenario of the most number of times you must press the button to guarantee the machine is in the targetState. If it is not possible to always ensure you can end on the targetState, return -1.

 

Definition

    
Class:SimpleIO
Method:worstCase
Parameters:String, int
Returns:int
Method signature:int worstCase(String pattern, int targetState)
(be sure your method is public)
    
 

Constraints

-pattern will have between 2 and 50 characters, inclusive.
-pattern will only contain the characters 'B' and 'N'.
-targetState will be between 0 and the length of pattern - 1, inclusive.
 

Examples

0)
    
"BNB"
0
Returns: 4
In the worst case, the first state is state 2. In this case, you press the button 2 times before we narrow down that the state is now state 1. You must now press the button 2 more times to get back to state 0.
1)
    
"BNBNBNBN"
3
Returns: -1
In this case, we can only tell if we are on an even or odd state, we cannot determine the exact state.
2)
    
"BBNNBNBBBBNBBBBBB"
3
Returns: 18

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

NumericalIntegral

Advanced Math, String Manipulation



Used in:

SRM 187

Used as:

Division I Level Two

Writer:

Rustyoldman

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2375

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4755&pm=2375

Problem Statement

    This problem contains HTML superscripts and images which will not display correctly for plugin users

Given two real numbers x1 and x2, calculate an approximation to the integral of e-x^2 evaluated between the limits from x1 to x2, which is accurate to the nearest 0.00001. Return the answer in a String, as a fixed point number with exactly five digits to the right of the decimal point and exactly one digit to the left of the decimal point.

For example: x1 = -0.5 and x2 = 0.5 returns "0.92256"

 

Definition

    
Class:NumericalIntegral
Method:integrate
Parameters:double, double
Returns:String
Method signature:String integrate(double x1, double x2)
(be sure your method is public)
    
 

Notes

-
  • e-x^2 can be calculated in C++ with exp(-x*x) in math.h.
  • e-x^2 can be calculated in C# with Math.Exp(-x*x). The Math class is in the System namespace.
  • e-x^2 can be calculated in Java with Math.exp(-x*x).
  • e-x^2 can be calculated in Visual Basic with Exp(-x*x) in the System.Math namespace.
-
-The integral of a function is the area inside the closed figure formed by (on the top) the function between the limits of x=x1 and x=x2, (on the sides) vertical line segments at x=x1 and x=x2, and (on the bottom) the portion of the x axis between x=x1 and x=x2. This is shown by the shaded area above (the graph shows the function we are integrating, e-x^2).
-The integral of e-x^2 is known to have no closed form, so don't waste time looking in a table of integrals for an exact formula.
-Because of the 2e-6 constraint, about 40% of randomly chosen x1 and x2 values will be too close to a possible rounding error and will be rejected. This is not an error. It gives you more room for numerical errors.
 

Constraints

-x1 will be less than x2.
-x2-x1 will be between 0.00001 and 1.00000 inclusive.
-x1 will be between -10.0 and 10.0 inclusive.
-x2 will be between -10.0 and 10.0 inclusive.
-To avoid rounding errors the inputs x1 and x2 must be chosen so that the answer is not within 2e-6 of 0.000005 + a multiple of 0.00001
 

Examples

0)
    
-0.5
0.5
Returns: "0.92256"
The example from above. This is the largest possible answer given the constraints of this problem.
1)
    
0.0
0.1
Returns: "0.09967"
2)
    
-9.0001
-9.0
Returns: "0.00000"
Values are very small out here.
3)
    
2.71828183
3.14159265
Returns: "0.00010"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

EulerianRace

Graph Theory, Simulation



Used in:

SRM 185

Used as:

Division I Level Two

Writer:

vorthys

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2373

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4745&pm=2373

Problem Statement

    

The city of Konigsberg is famous for its bridges. The Tour de Konigsberg is an annual bicycle race over a route that crosses each bridge exactly once. You are responsible for planning the route for this year's race.

A series of checkpoints numbered from 0 to N-1 have been set up around the city, with exactly one bridge between each pair of neighboring checkpoints. For example, here is a picture of the bridges and checkpoints from last year's race.

    0-------1
    |       |
    |       |
    |       |
    2-------3
    |\     /|
    | \   / |
    |  \ /  |
    4---5---6
(There has been substantial construction since last year, however, so the bridges and checkpoints for this year's race may be completely different.)

The route for the race must begin and end at checkpoint 0, and must proceed across the bridges from checkpoint to checkpoint, crossing each bridge exactly once. If the checkpoints are placed poorly, it might not be possible to come up with such a route, so the planner for the first Tour de Kongisberg, Leonhard Euler, was careful to leave instructions for how to lay out the checkpoints to guarantee that a successful race route will be possible. He decreed that the checkpoints should be placed with an even number of bridges (greater than zero) leaving each checkpoint, and furthermore that every checkpoint must be reachable from checkpoint 0. The checkpoints for this year's race were placed with Euler's instructions in mind. Now your task is to plan the race route. Fortunately, Euler also left notes telling you how.

You begin by laying out a tentative route that begins and ends at checkpoint 0. At every step along the way, this initial route leaves the current checkpoint via the unused bridge that leads to the lowest numbered checkpoint. When the tentative route returns to checkpoint 0, it may or may not have used all the bridges. If it has, you are done. Otherwise, you need to extend the route to use more bridges as follows. Beginning at checkpoint 0, you follow the tentative route until you reach a checkpoint--call it checkpoint K--that has an unused bridge leading out from it. (Note that K could be 0.) Lay out a new route by starting at checkpoint K and repeatedly taking the unused bridge that leads to the lowest numbered checkpoint until you return to checkpoint K. Now splice this new route into the tentative route after the first occurrence of K. Repeat this extension process on the new larger tentative route until all the bridges have been used. Note that you always restart the search for a checkpoint with an unused bridge back at the beginning of the tentative route; you do not continue from where you left off.

For example, in last year's race, the initial tentative route travelled from checkpoint 0 to 1 to 3 to 2. Marking the used bridges with x's we get

    0-x-x-x-1
    |       |
    x       x
    |       |
    2-x-x-x-3
    |\     /|
    | \   / |
    |  \ /  |
    4---5---6
Some bridges have not been used, so we retrace the tentative route until we reach checkpoint 3. Then we lay out a new route from checkpoint 3 to 5 to 2 to 4 to 5 to 6 to 3. Splicing this new route back into the original route, we end up with the final race route: 0-1-3-5-2-4-5-6-3-2-0.

You will be given a String[] bridges that contains information about which checkpoints are connected by bridges. The i-th character of element j of bridges is '1' if there is a bridge between checkpoints i and j. Otherwise, it is '0'. Note that both i and j are zero based. All bridges are two-way so a bridge between checkpoints i and j appears in bridges in both directions, from i to j and from j to i. You will return a int[] containing the sequence of checkpoints visited by the race route.

 

Definition

    
Class:EulerianRace
Method:planRoute
Parameters:String[]
Returns:int[]
Method signature:int[] planRoute(String[] bridges)
(be sure your method is public)
    
 

Constraints

-bridges contains between 3 and 30 elements, inclusive.
-Every element of bridges contains the same number of characters as elements in bridges.
-Every element in bridges contains only the characters '0' and/or '1'.
-Every element in bridges contains a positive even number of '1's.
-Character i of element i of bridges is '0'.
-Character i of element j of bridges is equal to character j of element i of bridges.
-Every checkpoint is reachable from checkpoint 0.
 

Examples

0)
    
{ "0110000",
  "1001000",
  "1001110",
  "0110011",
  "0010010",
  "0011101",
  "0001010" }
Returns: { 0,  1,  3,  5,  2,  4,  5,  6,  3,  2,  0 }
The example from last year's race.
1)
    
{ "0101000000",
  "1010110000",
  "0101000000",
  "1010000011",
  "0100011100",
  "0100100000",
  "0000100100",
  "0000101000",
  "0001000001",
  "0001000010" }
Returns: { 0,  1,  4,  6,  7,  4,  5,  1,  2,  3,  8,  9,  3,  0 }
In this example, the bridges and checkpoints are arranged as follows:
    0-------1---4---6
    |       |\  |\  |
    |       | \ | \ |
    |       |  \|  \|
    3-------2   5   7
    |\       
    | \      
    |  \     
    8---9
The initial tentative route is 0-1-2-3-0, which is then extended with 1-4-5-1 into 0-1-4-5-1-2-3-0. Next, it is extended with 4-6-7-4 into 0-1-4-6-7-4-5-1-2-3-0. Finally, it is extended with 3-8-9-0 into 0-1-4-6-7-4-5-1-2-3-8-9-3-0.
2)
    
{ "01111",
  "10111",
  "11011",
  "11101",
  "11110" }
Returns: { 0,  3,  2,  4,  3,  1,  4,  0,  1,  2,  0 }
A bridge between every possible pair of checkpoints.
3)
    
{ "01000000001",
  "10100000000",
  "01010000000",
  "00101000000",
  "00010100000",
  "00001010000",
  "00000101000",
  "00000010100",
  "00000001010",
  "00000000101",
  "10000000010" }
Returns: { 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10,  0 }
The bridges and checkpoints are arranged in a big circle.
4)
    
{ "00011",
  "00101",
  "01001",
  "10001",
  "11110" }
Returns: { 0,  3,  4,  1,  2,  4,  0 }
5)
    
{"011111111",
 "101000000",
 "110000000",
 "100010000",
 "100100000",
 "100000100",
 "100001000",
 "100000001",
 "100000010"}
Returns: { 0,  7,  8,  0,  5,  6,  0,  3,  4,  0,  1,  2,  0 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RecursiveGraph

Graph Theory



Used in:

SRM 188

Used as:

Division I Level Three

Writer:

legakis

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2365

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4760&pm=2365

Problem Statement

    

This problem statement contains an image which will not display correctly for plugin users.

You will be given an undirected graph which may contain several smaller copies of itself. These copies, or "children", will in turn recursively contain the same number of children, creating a graph with an infinite number of nodes. You are to find the shortest path through this graph.

At each level down, the edges of children have half the weight of their parent, rounded down. Once you recurse deep enough into the graph, all edges eventually have a weight of zero.

For example, consider the graph pictured above with 4 top-level nodes (A, B, C, and D), and 2 recursive children. Notice that each child has two smaller copies inside of it, and each of those children has two smaller copies inside of it, repeating infinitely. In this graph, there is a direct path from node A to B with distance 800. However, there is a shorter path from A to B that goes through C and D in the left-side child of the top-level graph. Within the left-side child, the path from C to D goes through A and B in its right-side child. The length of this 5-edge path is 4 + 2 + 200 + 2 + 4 = 212.

However, there is an even shorter path, bypassing the third-level edge from A to B with cost 200. By replacing this edge with the same 5-edge path two levels down, there is a 9-edge path with distance 4 + 2 + 1 + 0 + 50 + 0 + 1 + 2 + 4 = 64. Similarly, the edge with cost 50 can be bypassed again by recursing farther into the graph. By going down deep enough to the point where all edges have zero weight, the edge cost can be bypassed completely, resulting in a shortest path from A to B of length 4 + 2 + 1 + 0 + ... + 0 + 1 + 2 + 4 = 14.

Graphs will contain up to 10 top-level nodes ('A' through 'J'), and each parent graph at each level may contain up to 9 child graphs, smaller copies of itself, numbered ('1' through '9'). The graph will be specified by a list of edges in the top-level graph. Edges are specified by two nodes, followed by a weight. Either node may optionally be followed by a single digit, representing a connection to a node in the corresponding recursive copy of the graph.

The graph pictured above would be specified as:


    "A B 800" (connecting A and B in every copy of the graph)
    "A C1 4"  (connecting A in every copy to C in its first child)
    "D1 B 4"  (connecting B in every copy to D in its first child)
    "C A2 4"  (connecting C in every copy to A in its second child)
    "B2 D 4"  (connecting D in every copy to B in its second child)

There will be no edge that directly connects two nodes of the same child. For example, the edge "A3 B3 10" would be illegal, but the edge "A4 B5 20" is allowed. A top-level edge implies corresponding edges in all copies of the graph at all levels. Likewise, an edge connecting a top-level node to a copy implies corresponding connections between parents and children at all levels, and an edge connecting nodes of two different children implies corresponding edges between nodes in those two children at all levels.

Given a list of edges, a starting node, and an ending node, return the length of the shortest path between the starting and ending nodes. Return -1 if there is no such path, or if the distance of the shortest path is greater than 1,000,000,000.

 

Definition

    
Class:RecursiveGraph
Method:shortestPath
Parameters:String[], char, char
Returns:int
Method signature:int shortestPath(String[] edges, char start, char end)
(be sure your method is public)
    
 

Notes

-The shortest path may descend recursively down many levels.
-All edges are undirected. The order of a pair of nodes in the input is not significant.
-There can be no edges that connect nodes between levels with depths that differ by more than 1.
 

Constraints

-edges will contain between 1 and 50 elements, inclusive.
-Each element of edges will be formatted as "<node> <node> <weight>".
-Each <node> is a character between 'A' and 'J', inclusive, optionally followed by a digit between '1' and '9', inclusive.
-Each <weight> is an integer from 0 to 1000, inclusive, and will not have any leading zeros.
-There will be at most 10 top-level nodes (letters 'A' through 'J').
-At each level, there will be at most 9 copies of the graph embedded directly in itself (nodes with digits '1' through '9').
-There will not be more than one edge between the same two nodes.
-There will not be an edge connecting two nodes of the same recursive copy, i.e. "A1 B1 5" would be illegal input.
-start and end will each be a character between 'A' and 'J', inclusive, and will be nodes which appear in edges.
 

Examples

0)
    
{"A B 20",
"C D 13",
"A C1 1",
"D1 C2 2",
"D2 B 3"}
'A'
'B'
Returns: 18
This graph has 4 top-level nodes, plus two copies of itself. There are two paths from A to B. The direct path across the first edge has a cost of 20. However, the path through the two copies (A->C1->D1->C2->D2->B) has a weight of 1 + 6 + 2 + 6 + 3 = 18. Remember, the edges from C to D in the children have half the weight (rounded down) of the edge from C to D in their parent.
1)
    
{"A B 800",
"A C1 4",
"D1 B 4",
"C A2 4",
"B2 D 4"}
'A'
'B'
Returns: 14
This is the example from the problem statement.
2)
    
{"A A1 1",
"B B1 1"}
'A'
'B'
Returns: -1
No matter how far down you recurse, there is no path from A to B.
3)
    
{ "A E1 10", "H2 J 11",
"E F 50", "F1 G2 5", "G H 60",
"A C4 12", "D4 J 13",
"C E1 14", "F1 D 15",
"E G8 6", "F H8 8" }
'J'
'A'
Returns: 49
4)
    
{ "E H 3", "C J 3", "D E9 0", "H9 A 0", "A C3 0", "J3 F 0" }
'D'
'F'
Returns: 2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LinePlotter

Brute Force, Dynamic Programming, Geometry, Graph Theory, Search, String Parsing



Used in:

TCO04 Round 2

Used as:

Division I Level Two

Writer:

schveiguy

Testers:

PabloGilberto , lbackstrom , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2364

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5879&pm=2364

Problem Statement

    

On a plotter, the mechanical arm that draws on paper with a pen has a motor that can move it back and forth across the paper sideways. The plotter also has a paper motor, which can move the paper orthogonally to the plotter's arm, which effectively is like moving the pen up and down the paper. The paper is square, and is oriented so its lower edge is parallel to the arm. This allows the plotter to move to any coordinates using the two motors. Both motors can be active simultaneously, and each motor can move the pen up to one pixel per millisecond in relation to the paper (it's possible for a motor to run slower).

Given the list of lines that the plotter must put on the paper, return the minimum time it takes to plot the given lines, in milliseconds. The plotter's pen starts at the coordinates (0,0), and after drawing all the lines, must return to (0,0). Note that the plotter cannot draw partial lines. Each element of lines will be in the form "x1 y1 x2 y2". This represents a line from point (x1,y1) to point (x2,y2). It takes 0 time to lower the pen down on the paper, and to raise it off the paper.

 

Definition

    
Class:LinePlotter
Method:timeToPlot
Parameters:String[]
Returns:int
Method signature:int timeToPlot(String[] lines)
(be sure your method is public)
    
 

Notes

-There can be 0-length lines, which are drawn by moving to the designated location, lowering the pen and without moving, raising the pen.
 

Constraints

-lines will contain between 1 and 15 elements, inclusive.
-Each element of lines will be of the form "x1 y1 x2 y2", where each value is an integer between 0 and 9999, inclusive.
-There will be no extra leading zeros in any of the numbers in lines.
-There will be no repeated elements in lines. This includes lines which are reversed. For example, if "x1 y1 x2 y2" appears, then "x2 y2 x1 y1" cannot.
-No two lines can intersect at more than one point.
 

Examples

0)
    
{"0 1 1 0"}
Returns: 3
This is a line which draws a diagonal across the bottom corner of the paper. The line can be drawn by first running the arm motor to bring the pen over to (1,0) in 1 millisecond. Then the paper motor can be run simultaneously with the lateral motor to draw the line from (1,0) to (0,1) in one more millisecond. Finally, the paper motor brings the pen back to (0,0) in one more millisecond.
1)
    
{"0 0 5 5", "5 5 0 5", "0 100 0 4"}
Returns: 205
The best path first draws the line from (0,0) to (5,5). Since both motors can move at top speed, this line takes 5 milliseconds to draw. Without even picking up the pen, we can draw the line from (5,5) to (0,5) in 5 milliseconds. Finally, to draw the final line, we lift the pen, go all the way up to (0,100), and draw the line to (0,4). This adds 95 + 96 = 191 milliseconds. Finally, we lift the pen and move back to (0,0), adding an additional 4 milliseconds. The total time is 5 + 5 + 95 + 96 + 4 = 205 milliseconds.
2)
    
{"4647 8139 5695 458", "346 6987 5003 8789", "4955 4552 8216 4667",
 "1676 5564 9137 703", "2722 911 3594 2734", "1718 6222 4828 6335",
 "1265 5243 3677 2489", "2809 718 6675 9926", "5626 9254 8843 2486",
 "4938 6286 9083 1621", "2058 9050 3421 6083", "1648 1890 6058 2896",
 "6598 6029 8159 4543", "1279 634 5472 6714", "2295 4885 9765 5706"}
Returns: 92635

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Transpose

Graph Theory



Used in:

SRM 199

Used as:

Division II Level Three

Writer:

legakis

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2360

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5074&pm=2360

Problem Statement

    

NOTE: This problem statement contains subscripts and superscripts which may not display properly for plugin users.

The elements of a two-dimensional matrix with M rows and N columns are usually stored as a linear array of length M*N. Assuming "row-major" order, elements are stored left-to-right, then top-to-bottom (the same order that we read English text on a written page). For example, the following matrix A, with M=3 and N=3:


    0 1 2
    3 4 5
    6 7 8

is stored as: { 0, 1, 2, 3, 4, 5, 6, 7, 8 }.

The transpose of a matrix A (denoted AT) is obtained by exchanging its rows and columns. Element ATij equals Aji , and if A has M rows and N columns, AT will have N rows and M columns. For example, the transpose of the above matrix is:


    0 3 6
    1 4 7
    2 5 8

and is stored as: { 0, 3, 6, 1, 4, 7, 2, 5, 8 }.

Computing the transpose of the square matrix "in place" (overwriting the original matrix) in this example is easy: it involves swapping 3 pairs of elements: 1 and 3, 2 and 6, and 5 and 7. Elements 0, 4, and 8 do not need to be moved.

It is a bit more tricky when the matrix is not square. For example, the matrix:


    12 58 23
    81 74 96

is stored as { 12, 58, 23, 81, 74, 96 }. Its transpose is:


    12 81
    58 74 
    23 96

and is stored as: { 12, 81, 58, 74, 23, 96 }. This also requires 3 swaps. (See example 1 below.)

Given M and N, return the minimum number of swaps necessary to take the transpose of a matrix of that size in place.

 

Definition

    
Class:Transpose
Method:numSwaps
Parameters:int, int
Returns:int
Method signature:int numSwaps(int M, int N)
(be sure your method is public)
    
 

Notes

-Assume that you know nothing about the actual values of the elements in the matrix, and that you cannot reduce the number of swaps by looking for pairs of identical elements.
 

Constraints

-M and N will be between 1 and 100, inclusive.
 

Examples

0)
    
3
3
Returns: 3
This is the example above.
1)
    
2
3
Returns: 3
Initial array: { a, b, c, x, y, z }

Swap positions 1 and 2: { a, c, b, x, y, z }

Swap positions 1 and 3: { a, x, b, c, y, z }

Swap positions 3 and 4: { a, x, b, y, c, z }

After 3 swaps, the array has been transposed in place.
2)
    
3
5
Returns: 10
3)
    
50
50
Returns: 1225
4)
    
49
51
Returns: 2492

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TeamBuilder

Graph Theory



Used in:

SRM 184

Used as:

Division II Level Three

Writer:

Running Wild

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2356

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4740&pm=2356

Problem Statement

    You are arranging a weird game for a team building exercise. In this game there are certain locations that people can stand at, and from each location there are paths that lead to other locations, but there are not necessarily paths that lead directly back. You have everything set up, but you need to know two important numbers. There might be some locations from which every other location can be reached. There might also be locations that can be reached from every other location. You need to know how many of each of these there are.

Create a class TeamBuilder with a method specialLocations that takes a String[] paths that describes the way the locations have been connected, and returns a int[] with exactly two elements, the first one is the number of locations that can reach all other locations, and the second one is the number of locations that are reachable by all other locations. Each element of paths will be a String containing as many characters as there are elements in paths. The i-th element of paths (beginning with the 0-th element) will contain a '1' (all quotes are for clarity only) in position j if there is a path that leads directly from i to j, and a '0' if there is not a path that leads directly from i to j.
 

Definition

    
Class:TeamBuilder
Method:specialLocations
Parameters:String[]
Returns:int[]
Method signature:int[] specialLocations(String[] paths)
(be sure your method is public)
    
 

Constraints

-paths will contain between 2 and 50 elements, inclusive.
-Each element of paths will contain N characters, where N is the number of elements of paths.
-Each element of paths will contain only the characters '0' and '1'.
-The i-th element of paths will contain a zero in the i-th position.
 

Examples

0)
    
{"010","000","110"}
Returns: { 1,  1 }
Locations 0 and 2 can both reach location 1, and location 2 can reach both of the other locations, so we return {1,1}.
1)
    
{"0010","1000","1100","1000"}
Returns: { 1,  3 }
Only location 3 is able to reach all of the other locations, but it must take more than one path to reach locations 1 and 2. Locations 0, 1, and 2 are reachable by all other locations. The method returns {1,3}.
2)
    
{"01000","00100","00010","00001","10000"}
Returns: { 5,  5 }
Each location can reach one other, and the last one can reach the first, so all of them can reach all of the others.
3)
    
{"0110000","1000100","0000001","0010000","0110000","1000010","0001000"}
Returns: { 1,  3 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MagicianTour

Dynamic Programming, Graph Theory



Used in:

SRM 191

Used as:

Division I Level Three

Writer:

Ishan

Testers:

lbackstrom , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2346

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4775&pm=2346

Problem Statement

    You are a magician who has two different shows. You are planning a tour of a series of cities. Given the population of each city and the roads between cities, you must plan the tour such that no two cities directly connected by a road are assigned the same show and such that the difference between the number of people who see show 1 and those who see show 2 is minimized. You have to return the difference between the number of people who will see show 1 and those who will see show 2.



The roads between the cities are specified in the String[] roads. roads[i][j] is '1' if there is a road between the ith and jth cities and is '0' if there is no road. You are guaranteed that you can pull this off. (You can schedule the shows such that no two adjacent cities are assigned the same show.) Keep in mind that each city must be assigned one of the two shows. The population of each city is specified by the int[] populations whose ith element is the population of the ith city.
 

Definition

    
Class:MagicianTour
Method:bestDifference
Parameters:String[], int[]
Returns:int
Method signature:int bestDifference(String[] roads, int[] populations)
(be sure your method is public)
    
 

Notes

-You, the magician, can travel between two cities regardless of whether or not they are connected by a road.
 

Constraints

-populations contains between 1 and 50 elements, inclusive.
-roads contains exactly n elements, each of which has exactly n characters, where n is the number of elements in populations.
-Each element of populations will be between 0 and 20, inclusive.
-Each element of roads will only contain the characters '0' and '1'.
-You are guaranteed that you can schedule the shows such that no two adjacent cities are assigned the same show.
-No city will have a road to itself.
-The graph is undirected. Hence, if there is a road from city a to city b then there has to be a road from city b to city a. As a result, roads[i][j] and roads[j][i] must be the same.
 

Examples

0)
    
{"01","10"}
{15,20}
Returns: 5
There are two cities of populations 15 and 20. Perform show 1 in the first and show 2 in the second or vice versa.
1)
    
{"0100",
 "1000",
 "0001",
 "0010"}
{2,4,2,4}
Returns: 0
There are four cities of populations 2, 4, 2 and 4. Perform show 1 in the first and fourth cities and perform show 2 in the second and third cities.
2)
    
{"0010",
 "0001",
 "1000",
 "0100"}
{2,2,2,2}
Returns: 0
3)
    
{"000",
 "000",
 "000"}
{6,7,15}
Returns: 2
There are no roads! To keep it balanced, perform show 1 in the first and second cities and show 2 in the third city.
4)
    
{"0000",
 "0010",
 "0101",
 "0010"}
{8,10,15,10}
Returns: 3
5)
    
{"010",
 "101",
 "010"}
{5,1,5}
Returns: 9
6)
    
{
"01000000000000000000000000000000000",
"10100000000000000000000000000000000",
"01010000000000000000000000000000000",
"00101000000000000000000000000000000",
"00010100000000000000000000000000000",
"00001010000000000000000000000000000",
"00000101000000000000000000000000000",
"00000010100000000000000000000000000",
"00000001010000000000000000000000000",
"00000000101000000000000000000000000",
"00000000010100000000000000000000000",
"00000000001010000000000000000000000",
"00000000000101000000000000000000000",
"00000000000010100000000000000000000",
"00000000000001010000000000000000000",
"00000000000000101000000000000000000",
"00000000000000010100000000000000000",
"00000000000000001010000000000000000",
"00000000000000000100000000000000000",
"00000000000000000000000000000000000",
"00000000000000000000010000000000000",
"00000000000000000000101000000000000",
"00000000000000000000010100000000000",
"00000000000000000000001010000000000",
"00000000000000000000000101000000000",
"00000000000000000000000010100000000",
"00000000000000000000000001010000000",
"00000000000000000000000000101000000",
"00000000000000000000000000010100000",
"00000000000000000000000000001010000",
"00000000000000000000000000000101000",
"00000000000000000000000000000010100",
"00000000000000000000000000000001010",
"00000000000000000000000000000000101",
"00000000000000000000000000000000010"
}
{8,15,12,9,12,6,4,6,16,1,15,3,18,15,14,8,6,6,12,13,14,15,17,15,3,8,7,8,3,19,12,9,14,19,9}
Returns: 21

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TeamBuilding

Graph Theory



Used in:

SRM 184

Used as:

Division I Level Three

Writer:

Running Wild

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2327

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4740&pm=2327

Problem Statement

    You are arranging a weird game for a team building exercise. In this game there are certain locations that people can stand at, and from each location there are paths that lead to other locations, but there are not necessarily paths that lead directly back. You want the paths set up such that regardless of where someone starts, there will be at least one path they can take that will return to their starting location. You already have the locations set up, and some paths connecting them. You want to know the fewest paths that you have to add such that everything is set up the way you need it.



Create a class TeamBuilding with a method fewestPaths that takes a String[] paths that describes the way the locations are currently connected, and returns an int that is the fewest number of paths that must be added. Each element of paths will be a String containing as many characters as there are elements in paths. The i-th element of paths (beginning with the 0-th element) will contain a '1' (all quotes are for clarity only) in position j if there is a path that leads directly from i to j, and a '0' if there is not a path that leads directly from i to j.
 

Definition

    
Class:TeamBuilding
Method:fewestPaths
Parameters:String[]
Returns:int
Method signature:int fewestPaths(String[] paths)
(be sure your method is public)
    
 

Notes

-There may be paths that leads directly from one location to that same location.
 

Constraints

-paths will contain between 2 and 20 elements, inclusive.
-Each element of paths will contain only the characters '0' and '1'.
-Each element of paths will contain as many characters as there are elements in paths.
 

Examples

0)
    
{"010",
 "100",
 "000"}
Returns: 1
There are paths leaading from location 0 to location 1, and from location 1 to location 0. By adding a path from location 2 to itself, all locations will be able to follow a set of paths that lead back to themselves.
1)
    
{"0110",
 "0001",
 "0101",
 "1000"}
Returns: 0
There already exists a set of paths for each location that leads back to itself.
2)
    
{"00101",
 "00010",
 "00010",
 "10000",
 "00000"}
Returns: 1
3)
    
{"001000000",
 "000000010",
 "000001000",
 "000010010",
 "000000000",
 "000000010",
 "000000000",
 "100000001",
 "010000100"}
Returns: 2

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WordPuzzle

Dynamic Programming, Recursion, Search



Used in:

TCCC '04 Wildcard

Used as:

Division I Level One

Writer:

schveiguy

Testers:

lbackstrom , brett1479 , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2298

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5079&pm=2298

Problem Statement

    

In some popular word puzzles from newspapers, you are to convert a word into another word by either swapping letters, or changing one letter to another. However, one constraint is that the characters formed by each move MUST be a real word.

Your method will be given a String source that should be converted to a String target. You will also be given a String[] dictionary, where each element is a word you are allowed to use in the conversion. At each step, you can either swap two (not necessarily adjacent) characters in a word, or change one letter in a word. The new word must be either target or one of the words from dictionary. The return value will be a String[] containing the words used to do the conversion, in the order they were used. The first element in the return value should be source, the last element should be target. If multiple ways exist to convert from one word to the other, you should return the one with the smallest number of intermediate words. If two sequences exist that have the same number of intermediate words, return the sequence which is smallest lexicographically. Sequence A is lexicographically smaller than sequence B if the first string A[i] that differs from B[i] is lexicographically smaller than B[i]. String A[i] is lexicographically smaller than B[i] if the first character A[i][j] that differs from B[i][j] comes before B[i][j] alphabetically. All words in the input will be the same length. If no conversion is possible, return an empty String[].

 

Definition

    
Class:WordPuzzle
Method:getConversions
Parameters:String[], String, String
Returns:String[]
Method signature:String[] getConversions(String[] dictionary, String source, String target)
(be sure your method is public)
    
 

Notes

-The words in the input might or might not be actual English words or words from any other language. See example 3.
 

Constraints

-dictionary has between 1 and 50 elements, inclusive.
-source has between 4 and 50 characters, inclusive.
-target has the same number of characters as source.
-All elements in dictionary have the same number of characters as source.
-source, target, and all elements of dictionary will consist only of lowercase letters ('a'-'z').
-source will not be the same as target.
-source and target will not appear in dictionary.
-There will be no repeated elements in dictionary.
 

Examples

0)
    
{"fowl","foal","loaf","load","loan","loon","toon"}
"foul"
"tool"
Returns: { "foul",  "foal",  "loaf",  "loan",  "loon",  "toon",  "tool" }
Note that although in the given list of words, each element can achieve the next, you can skip over "fowl" and "load" since you can go directly from "foul" to "foal", and directly from "loaf" to "loan".
1)
    
{"stew","wets"}
"stow"
"west"
Returns: { }
Only two letters can be swapped at once.
2)
    
{"flew", "slew", "stew", "stow"}
"flow"
"slow"
Returns: { "flow",  "slow" }
In this conversion, no words from the dictionary were necessary.
3)
    
{"tsray","trsay","trasy"}
"stray"
"trays"
Returns: { "stray",  "tsray",  "trsay",  "trasy",  "trays" }
Note that you cannot simply remove the 's' and insert it at the end.
4)
    
{"toon","loot"}
"loon"
"tool"
Returns: { "loon",  "loot",  "tool" }

The following is also a conversion with three words, but is lexicographically larger than the answer:

loon -> toon -> tool

5)
    
{"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaay",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaax",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaw",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaav",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaau",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaat",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaas",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaq",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaap",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaao",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaan",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaak",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaj",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaai",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaag",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaf",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaae",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaad",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "yaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "waaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "vaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "uaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "taaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "saaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "raaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "qaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "oaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "maaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "laaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "kaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "jaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "iaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "haaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "gaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "faaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "eaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "daaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "caaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "zaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "caaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz"}
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"zaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz"
Returns: 
{ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "zaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
 "zaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RandomFA

Dynamic Programming, Graph Theory, Math



Used in:

SRM 178

Used as:

Division I Level Two

Writer:

brett1479

Testers:

lbackstrom , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2287

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4710&pm=2287

Problem Statement

    A Randomized Finite Automaton (RFA) works as follows. The RFA maintains a variable, called its state, which is initially set to 0. When an input character ('a', 'b', or 'c') is fed into the RFA, it must determine which new value is to be assigned to its state. This determining process is governed by a list of rules stored in the RFA. For example, if the RFA is in state 2 and has received an 'a' as input, the RFA would consult element 2 of rulesa. Each element of rulesa is of the form "st:prob st:prob ...", where st denotes a value to be assigned to the state variable, and prob denotes the percentage (out of 100) of such an assignment occurring. If the given probabilities do not add up to 100, the remaining probability is the chance of changing state to 999. If a state (not 999) is missing from a rule, then its prob is assumed to be 0. Once state is 999, regardless of future input, it remains on 999. The machine has analogously defined rulesb, and rulesc defining what to do on 'b' or 'c' accordingly.



When processing an input string, each character is processed in order, left to right, one at a time. Assuming all input strings of length maxLength or fewer (including the string of length 0) are equally likely, return the probability the RFA will be on state finalState once the string is completely processed. The probability returned will be a double, between 0 and 1 inclusive. Results must be accurate to 1e-9.
 

Definition

    
Class:RandomFA
Method:getProbability
Parameters:String[], String[], String[], int, int
Returns:double
Method signature:double getProbability(String[] rulesa, String[] rulesb, String[] rulesc, int finalState, int maxLength)
(be sure your method is public)
    
 

Constraints

-rulesa will contain between 1 and 50 elements inclusive.
-rulesa, rulesb, and rulesc all contain the same number of elements.
-Each element of rulesa, rulesb, and rulesc contain between 0 and 50 characters inclusive.
-Each element of rulesa, rulesb, and rulesc is a single space delimited list of pairs. Each pair is of the form (quotes for clarity) "st:prob" where,

st is an integer, with no extra leading zeros, between 0 and (size of rulesa-1) inclusive, and

prob is a positive integer, with no leading zeros.
-The prob values in a single element of rulesa, rulesb, or rulesc will sum up to a value between 0 and 100 inclusive.
-No 2 pairs in a single element of rulesa, rulesb, or rulesc will have the same st value.
-finalState will be between 0 and (size of rulesa-1) inclusive, or 999.
-maxLength will be between 0 and 10 inclusive.
 

Examples

0)
    
{"0:100"}
{""}
{""}
999
1
Returns: 0.5
The 4 strings that need to be considered are (quotes for clarity) "", "a", "b", and "c". Of those 4, the first 2 will end up on state 0, while the latter 2 will end up on state 999. 2 out of 4 produces a probability of .5 .
1)
    
{"1:100","0:100"}
{"1:100","0:100"}
{"1:100","0:100"}
1
3
Returns: 0.75
Here all even length strings will result in state 0, and odd length strings will result in state 1. Of the 40 strings considered, 1 has length 0, 3 have length 1, 9 have length 2, and 27 have length 3. Thus 30/40=.75 of them have odd length.
2)
    
{"1:25 2:25 3:25 4:25","0:100","0:100","0:100","0:100"}
{"","","","",""}
{"","","","",""}
3
5
Returns: 0.0020604395604395605
All strings that contain a 'b', or 'c' are sent to 999. The strings containing only 'a's begin on state 0, and are evenly distributed between states 1,2,3 and 4 after the first 'a'. After the second 'a' they are all returned to state 0. Examining this pattern, we see that strings that end on state 3 must contain only 'a's and have odd length. Of those, only a quarter of them actually make it to state 3. There are 3 strings consisting of only 'a's that have odd lengths less than or equal 5. This makes 3 out of the total 364 strings. The returned probability is thus 3/364*.25 = .0021 approx.
3)
    
{"1:25 2:25 3:25 4:25","0:100","0:100","0:100","0:100"}
{"","","","",""}
{"","","","",""}
999
5
Returns: 0.9835164835164837
The same problem as before, but now we want the strings that will end on 999. This will be any string of positive length that has a 'b' or 'c'. There are 358 of these, resulting in a probability of 358/364 = .984 approx.
4)
    
{"2:9 0:7 3:4 1:2 5:35","2:9 0:7 3:4 1:2 5:35",
 "2:9 0:7 3:4 1:2 5:35","2:9 0:7 3:4 1:2 5:35",
 "2:9 0:7 3:4 1:2 5:35","2:9 0:7 3:4 1:2 5:35"}
{"0:10 4:7 5:1","0:10 4:7 5:1","0:10 4:7 5:1",
 "0:10 4:7 5:1","0:10 4:7 5:1","3:79 2:10"}
{"1:100","2:100","3:100","4:100","5:100","0:100"}
3
10
Returns: 0.002676338903044717
A more complex example.
5)
    
{"2:9 0:7 3:4 1:2 5:35","2:9 0:7 3:4 1:2 5:35",
 "2:9 0:7 3:4 1:2 5:35","2:9 0:7 3:4 1:2 5:35",
 "2:9 0:7 3:4 1:2 5:35","2:9 0:7 3:4 1:2 5:35"}
{"0:10 4:7 5:1","0:10 4:7 5:1","0:10 4:7 5:1",
 "0:10 4:7 5:1","0:10 4:7 5:1","3:79 2:10"}
{"1:100","2:100","3:100","4:100","5:100","0:100"}
3
0
Returns: 0.0
Same as before, but only the empty string is considered.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TextColumns

String Manipulation, String Parsing



Used in:

TCCC '04 Semifinals 2

Used as:

Division I Level One

Writer:

Yarin

Testers:

zoidal , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2275

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5077&pm=2275

Problem Statement

    

An OCR program (optical character recognition) needs to perform other things than just recognizing letters. One of these things is mapping out the page layout. In this problem, you should solve the similar, but easier task, of concatenating text spread across several text columns.

The input text will be given as a String[] and split up into several text columns. Consider for instance the text below: (quotes are for clarity only)

{"  This is       put  it      that       ",
 " a text          all       is           ",
 "in  several    together      nicely     ",
 "columns.       into  a      formatted.  ",
 "               single                   ",
 " Your  job        text                  ",
 "is     to                   Good luck!  "}

The text above obviously has three text columns. Formally, text columns are always separated where there are three or more consecutive empty character columns (i.e. the only character in those columns are space). Furthermore, text columns can't be empty (see example 3).

You should also find all paragraphs. The paragraph splits occur on blank lines within a text column. Only blank lines between the first and last row used in a text column should be considered. In the text above, the last line in column two is empty, but this is not a paragraph split because there is no text below this line in the same text column.

The return value should contain the same text, in a String[], but where each element corresponds to one paragraph. Empty paragraphs should be ignored (that is, there should be no empty strings). Leading and trailing spaces should be removed in each paragraph, and consecutive spaces should be replaced by a single space. Line breaks within a paragraph should also be replaced by a single space so the last word on a line is not concatenated with the first word on the next line.

Create a class TextColumns containing the method formatText which takes a String[] text containing the text and which returns a String[], containing the formatted text in the format described above. See the examples for further explanations.

 

Definition

    
Class:TextColumns
Method:formatText
Parameters:String[]
Returns:String[]
Method signature:String[] formatText(String[] text)
(be sure your method is public)
    
 

Constraints

-text will contain between 1 and 50 elements inclusive.
-Each element in text will contain between 1 and 50 characters, inclusive.
-All elements in text will contain the same number of characters.
-text will only contain the characters 'A'-'Z', 'a'-'z', '0'-'9', '.', ',', '!', '?' and space.
-At least one character in text will not be a space.
 

Examples

0)
    
{"  This is       put  it      that       ",
 " a text          all       is           ",
 "in  several    together      nicely     ",
 "columns.       into  a      formatted.  ",
 "               single                   ",
 " Your  job        text                  ",
 "is     to                   Good luck!  "}
Returns: 
{ "This is a text in several columns.",
 "Your job is to put it all together into a single text that is nicely formatted.",
 "Good luck!" }
This is the example in the problem statement.
1)
    
{"This is                                    ",
 "just one                                   ",
 "column                                     ",
 "                                           ",
 "a                 l                        ",
 "   b                 m                     ",
 "      c                 n                  ",
 "         d                 o               ",
 "            e                 p            ",
 "               f                 q         ",
 "            g                 r            ",
 "         h                 s               ",
 "      i                 t                  ",
 "   j                 u                     ",
 "k                 v                        "}
Returns: { "This is just one column",  "a l b m c n d o e p f q g r h s i t j u k v" }
2)
    
{"                                    ",
 "                                    ",
 " Some text                          ",
 " here and                           ",
 "  some                              ",
 "                                    ",
 "                            new     ",
 "                                over",
 "                             here   ",
 "                text                ",
 "                  there             ",
 "                                    ",
 "                                    ",
 "                   And              ",
 "             something              ",
 "                                    ",
 "                                    ",
 "                             Finito ",
 "                                    "}
Returns: 
{ "Some text here and some text there",
 "And something new over here",
 "Finito" }
3)
    
{"    Column 1                                      ",
 "                   Column 2                       ",
 "                                   Column 3       "}
Returns: { "Column 1 Column 2 Column 3" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BombMan

Graph Theory, Search



Used in:

TCCC '04 Round 4

Used as:

Division I Level Two

Writer:

Yarin

Testers:

lbackstrom , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2274

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5009&pm=2274

Problem Statement

    

Bomb Man is trapped inside a maze shaped like a grid. You must help him find the exit as fast as possible. The maze will be given as a String[] where each element corresponds to a row in the grid and each character in an element corresponds to a cell in that row. '#' marks a wall, '.' an empty cell, 'B' the start position of Bomb Man and 'E' the exit. Below is an example of a maze in this format, given as a String[]:

{".....B.",
 ".#####.",
 ".#...#.",
 ".#E#.#.",
 ".###.#.",
 "......."}

In each time unit, Bomb Man can move one cell up, down, left or right. Thus, in the maze above, he can reach the exit in 14 time units by just walking.

To be able to reach the exit quicker, Bomb Man is in possession of a number of bombs, each of which can blow a hole in a wall and thus open up new passages. Instead of moving in any of the four cardinal directions, Bomb Man can (if he has bombs left) blow a hole in a wall located in any of the four neighboring squares. The bomb will go off in the time unit after he has placed the bomb, creating an empty cell that Bomb Man can enter in the time unit after that. That is, if he places a bomb in time unit t, he can enter the cell earliest in time unit t+2. In the maze above, Bomb Man can then reach the exit in 8 time units by first walking left, placing a bomb, waiting for the bomb to explode, and then walking down, down, left, left and down.

Create a class BombMan containing the method shortestPath which takes a String[] maze, containing the maze in the format described above, and an int bombs, the number of bombs in Bomb Man's possession. The method should return an int, the least number of time units required for Bomb Man to reach the exit. If it's not possible for Bomb Man to reach the exit, return -1 (see example 1).

 

Definition

    
Class:BombMan
Method:shortestPath
Parameters:String[], int
Returns:int
Method signature:int shortestPath(String[] maze, int bombs)
(be sure your method is public)
    
 

Constraints

-maze will contain between 1 and 50 elements, inclusive.
-Each element in maze will contain between 1 and 50 characters, inclusive.
-Each element in maze will contain the same number of characters.
-maze will only contain the characters '#', '.', 'B' and 'E'.
-Exactly one character in maze will be a 'B'.
-Exactly one character in maze will be a 'E'.
-bombs will be between 0 and 100, inclusive.
 

Examples

0)
    
{".....B.",
 ".#####.",
 ".#...#.",
 ".#E#.#.",
 ".###.#.",
 "......."}
1
Returns: 8
This is the example mentioned in the problem statement.
1)
    
{"B.#.#.#...E"}
2
Returns: -1
Bomb Man can only blow through the first two walls, but not the third. Hence the method returns -1.
2)
    
{"..#####",
 "B.#####",
 "..#####",
 "#######",
 "####...",
 "####.E."}
4
Returns: 17
Here Bomb Man has just enough bombs to reach the exit. One way to do this is to walk down, right, down (bomb), down (bomb), right (bomb), right (bomb), right, right, down. This takes 1+1+3+3+3+3+1+1+1 = 17 time units.
3)
    
{".#.#.#.#B#...#.#...#.#...#.#...#.#...#.#.#.......",
 ".#.#.#.#.#.###.###.#.###.#.#.###.###.#.#.#.###.##",
 ".#.#.#...#.#.#.#.#.#...#.....#.#.#...#...#.#.#...",
 ".#.#.###.#.#.#.#.#.###.#.#####.#.###.###.#.#.###.",
 ".............#.#...#...#.....#.#.#...#.#.#.....#.",
 "##.#######.###.#.#####.#.#####.#.###.#.#.#.#.####",
 ".#.#.....#...#...#.#...#...#.#.#...#...#...#.....",
 ".#######.#.#####.#.#.#.#.###.#.###.#.#####.#.####",
 ".#.#.#.#...#.#.#.#.#.#.......#...#.#...#.#.#.....",
 ".#.#.#.###.#.#.#.#.#####.#####.###.###.#.#.######",
 ".....#...#.#...#...#...#...#...#...#.#.#.........",
 "####.###.#.###.###.#.###.#.#.###.###.#.#.########",
 ".......#.........#.#.#.#.#.#.#.#.........#...#...",
 ".#.###.#########.#.#.#.#.###.#.#####.#.#.#.###.##",
 ".#.#.........#.#.#.#.#.....#.#.#.....#.#.........",
 "############.#.#.#.#.#.#####.#.#.################",
 ".#...........#...#.#.#.#...#.#.#...#.#.#.....#...",
 ".#####.#####.###.#.#.#.#.###.#.#.###.#.#.#####.##",
 ".......#...#.#.#.....#...#...#.#.#.#.#...........",
 "##########.#.#.#####.#.###.###.#.#.#.#.##########",
 ".....#...#.....#.#...#.......#.#...#.......#.....",
 "##.#.###.#.###.#.#.#.#.#####.#.#.###.#######.####",
 "...#...#...#.......#.....#.#...#...#.......#.....",
 "####.#.#.#########.#.###.#.#####.###.#.#######.##",
 ".#...#...#.........#.#.....#.........#.#.#.#.....",
 ".#####.#.#.###.#######.#.###.#.#########.#.#.####",
 ".......#.#.#...#.......#.....#.#.#.......#.#.#.#.",
 "########.#.#.#.#####.#.###.#.###.#.#######.#.#.#.",
 ".........#.#.#.#.....#...#.#.........#.#.........",
 "################.#.#.#.#.#.#.#.#######.#.########",
 ".................#.#.#.#.#.#.#...........#.......",
 "########.#####.#.###.#.#.#####.###.#.#####.###.##",
 ".........#...#.#...#.#.#...#.....#.#.........#...",
 ".#####.#####.#.###.#.###.#.#.#.#.#.#####.#.###.#.",
 ".#.....#.........#.#.#...#.#.#.#.#.#.....#...#.#.",
 "####.#####.###.#.#.#.#.#.#.###.###.#.#.#.#.#####.",
 ".....#.....#.#.#.#.#.#.#.#.#...#...#.#.#.#...#...",
 "####.#.#.###.#.#.###.#.###.#.#.#####.#.#.#.######",
 ".....#.#.#.#...#...#.#...#.#.#...#...#.#.#.......",
 "##########.#.#.#.#####.###.#.#.###.#.###.#####.##",
 "...#.#...#...#.#.....#.#...#.#...#.#.#.......#...",
 ".#.#.#.#.#.#.#.#.#.#.###.#.#########.###.#.#.#.#.",
 ".#.#...#...#.#.#.#.#...#.#...#.......#...#.#.#.#.",
 "##.###.#.#.###.#.#.#.#.#####.#.#.#.###.#.########",
 ".......#.#...#.#.#.#.#.#.....#.#.#...#.#.........",
 "####.#######.#.#####.#.###.#.#.###.#.#.#.########",
 "E..#.......#.#.....#.#.#.#.#.#.#...#.#.#.........",
 "##.#.#.#.###.###.###.###.#.#.###.#.#.#.#.#######.",
 ".....#.#...#.#.....#.#.....#...#.#.#.#.#.....#..."}
3
Returns: 76

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TrueFalse

Brute Force



Used in:

SRM 181

Used as:

Division I Level Two

Writer:

antimatter

Testers:

lbackstrom , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2253

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4725&pm=2253

Problem Statement

    

Throughout the term in computer science class, Professor Smith's exams consisted entirely of true or false questions. The reason? He was too lazy to grade things by hand, so after a test was over, he would input each student's answers into his computer, and the grades would be automatically calculated. Easy!

It is the end of the term now, and grades are due tomorrow. As luck would have it, Smith's computer has crashed, and he has no time to try and fix it. All he can do now is to try and dig up old test papers and regrade them by hand.

The problem is, the answer keys for all the tests were on the computer. So now, he must try and reconstruct the answer keys so that he can grade things. All is not lost, however. He has all of the papers stored, and he can remember the number of correct answers for certain students. In addition, he is sure each question was answered correctly by at least one student. However, he still hasn't been able to figure out the answer keys for some of them, and he's asked you for help.

For some given test, the papers for which he can remember grades are given as a String[] graded. Each String represents a single student's graded test paper for this specific test, and will start off with a non-negative integer without extra leading zeros indicating the number of questions that student got correct. Then that number is followed by a single space, and then a sequence of uppercase 'T's and 'F's, where the first represents that student's answer to the first question ('T' = true, 'F' = false), and so on. Your method should return the lexicographically earliest answer key that is consistent with the grades he remembers as a String, with the first character being the correct answer to the first question, the second character being the correct answer to the second, and so on. If there is no answer key that works, your method should return the String "inconsistent" (without the double quotes).

 

Definition

    
Class:TrueFalse
Method:answerKey
Parameters:String[]
Returns:String
Method signature:String answerKey(String[] graded)
(be sure your method is public)
    
 

Notes

-Each question has been answered correctly by at least one student. (See example 0.)
 

Constraints

-graded will contain between 1 and 50 elements, inclusive.
-each element of graded will be between 3 and 18 characters in length, inclusive.
-each element of graded will contain a number N without extra leading zeros, followed by one space and then a sequence of 'T's and 'F's.
-each element of graded will have the same number of letters following the number.
-for each element of graded, N will be between 0 and the number of letters in each element, inclusive.
 

Examples

0)
    
{"2 TTF",
 "1 FTF",
 "2 FTT"}
Returns: "TTT"
Since the second question was answered 'T' by all of them, it must be right, since every question was answered correctly by at least one student. Then the second person's test paper tells us that the only possible correct answer key is "TTT", which is consistent with the other two students' papers.
1)
    
{"7 TTFFTFT"}
Returns: "TTFFTFT"
Only one person, and he had a perfect score.
2)
    
{"9 TTTFFFFTTFFTTFT",
 "7 FFFFFFFFFFFFFFF"}
Returns: "inconsistent"
3)
    
{"9 TTTFFFFTTFFTTFT",
 "7 FFFFFFFFFFFFFFF",
 "8 TTTTTTTTTTTTTTT"}
Returns: "FFFFFFFTTTTTTTT"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BinaryQuipu

Graph Theory



Used in:

SRM 175

Used as:

Division I Level Three

Writer:

Eeyore

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2239

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4680&pm=2239

Problem Statement

    

Warning: Embedded in this problem statement are images that may not be visible if you are using a plugin. For best results, view this problem in the standard Arena editor.

"To heck with this quipu!" exclaimed Tupac the Incan philosopher. He was trying to record the contents of his household using the knot language of Peru, but the rules were too complicated. Who besides a tax collector could keep track of all the fixed knots, transient knots, and rhetorical knots?

After some thought, Tupac contrived a simpler scheme that would encode each inventory item on a length of string using a sequence of square knots and bow knots. For one particular collection of four items, he tied the following four strings, where 's' stands for a square knot and 'b' for a bow knot: {"bsb", "bbs", "sbbs", "sbs"}.

This took 13 knots. Tupac now gathered the strings into a quipu by tying them at one end with a top knot, making a grand total of 14 knots. The result of his efforts is depicted in the following image, where the bow knots are colored blue; the square knots, red; and the top knot, black.

"The top knot is important," explained Tupac to his wife, Cuxi, "because it shows me where to start reading each item."

"Let me see that," said Cuxi, reaching for the quipu. "I can record the same four items using fewer knots."

Once Cuxi had cut off some parts of the quipu and reknotted a few others, it emerged like so.

Her husband goggled at this feat. "Three knots fewer!" he cried. "And it encodes exactly the same inventory!"

Tupac saw that if he began from the top knot and followed a path through the quipu from left to right until the end of a string, he could spell out any inventory item, but nothing that wasn't in the inventory. This was an improvement over the original quipu, in which he sometimes found himself reading the wrong item and therefore having to backtrack to the top knot.

"I can do better yet," said Cuxi, "if I join some strings at the other end of the quipu. Watch this." After some more cutting and reknotting, she produced the following configuration.

Cuxi stated emphatically that you weren't supposed to pursue a looping path through the quipu. "Follow the grain of the string from beginning to end," she said, "and make sure you don't double back. The quipu only works in one direction."

She also pointed out that the paths were deterministic: at every knot where the quipu bifurcated, there was a choice of two different knots. This guaranteed that any inventory item could be found without backtracking or pursuing several paths at once.

Tupac was pleased to confirm that Cuxi's abbreviated quipu was functionally equivalent to the original. He could begin reading from the top knot and proceed strictly from left to right through the knots, following one of four distinct paths that spelled out exactly the items of the inventory.

"I can't make it any smaller," said Cuxi, "but a quipu with eight knots is an improvement over the original fourteen. So I'm pretty good. I'm only worried about cases where one item in the inventory is a prefix of another."

"There will never be such a case," said Tupac. "As it happens, my inventory encoding has the property that no item can be a prefix of another."

You are given a String[] describing a collection of inventory items encoded under Tupac's system. Calculate the smallest number of knots, including the top knot, that must be tied to make a deterministic binary quipu for this inventory.

 

Definition

    
Class:BinaryQuipu
Method:fewestKnots
Parameters:String[]
Returns:int
Method signature:int fewestKnots(String[] inventory)
(be sure your method is public)
    
 

Notes

-Since Tupac's encoding precludes any inventory where one item is a prefix of another, there will be no duplicates.
 

Constraints

-inventory contains between 1 and 50 elements, inclusive
-each element of inventory is between 1 and 50 characters long, inclusive
-no element of inventory is a prefix of any other element
-each character in every element of inventory is either 's' or 'b'
 

Examples

0)
    
{"bsb", "bbs", "sbbs", "sbs"}
Returns: 8
This is the example shown above.
1)
    
{"s", "b"}
Returns: 3
2)
    
{"bs", "sb"}
Returns: 5
3)
    
{"bs", "sb", "bb", "ss"}
Returns: 5
4)
    
{"bssbs", "ssbs", "sbb", "bbs", "sbs", "ssbb"}
Returns: 10
5)
    
{"bbbsssbbsbbssbbbbs",
"bssssbbbbsbbsbbbbbbsbbsbsssbbbsbbbbbsbbssbsb",
"sbbbbbsbbbsbsssbssssbssbbsssssssbbssss",
"sbbbbbsbsbssbssbsssbsbbsbssbsbbbsbsbs",
"bsbbbbbssbsbbbbsbbs",
"bbsbbsbsssbsbbsbbssbbbsbsssbsbbsbsbssbsbsssbsbsbs"}
Returns: 181

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DataFilter

Graph Theory



Used in:

TCCC '04 Finals

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

lbackstrom , schveiguy , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2010

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5080&pm=2010

Problem Statement

    Name, age, and id. That is the information that we are supposed to have for all our workers, but what we have is a mess. Our data is a collection of records, but some workers have multiple records, and some of the records are missing some of the information. We would like to untangle the mess. At least, we would like to figure out how many different workers we have!

Each worker has his own unique id that is a string of digits, the first of which is always zero ('0'). Each worker has a name consisting of uppercase letters 'A'-'Z', and has an age that is an integer with no leading zeros. Neither name nor age can be relied upon to be unique. Each data record contains information for a single worker, and is formatted to contain no leading or trailing spaces. It may contain 1, 2, or all 3 of the fields (name, age, id) in any order. The fields within a record will be separated by one or more spaces.

Create a class DataFilter that contains a method untangle that is given a String[] data that contains the records and returns the number of different workers we have.

Each element of data consists of one or more records, separated from each other by a single semicolon (';'). If there is more than one way to untangle the data, return the smallest possible number of workers. If there is no consistent interpretation of the data, return -1.

 

Definition

    
Class:DataFilter
Method:untangle
Parameters:String[]
Returns:int
Method signature:int untangle(String[] data)
(be sure your method is public)
    
 

Notes

-Ids should be treated as strings, not numbers.
 

Constraints

-data will contain between 1 and 50 elements inclusive.
-Each element of data will contain between 1 and 50 characters inclusive.
-Each element of data will consist of 1 or more records, separated from each other by a single ';'
-Each record in each element of data will contain no leading or trailing spaces.
-Each record will contain exactly 1, 2, or 3 fields separated by (possibly multiple) spaces.
-No record will contain more than one age, name, or id.
-Each age will be between 1 and 150 inclusive, and will not have a leading '0'
-Each id will contain between 1 and 10 characters inclusive, all digits and having a leading '0'
-Each name will contain between 1 and 10 characters inclusive, all uppercase letters 'A'-'Z'
 

Examples

0)
    
{"BOB      22 013","17 BOB;22","0234","16"} 
Returns: 3
data consists of 5 records (one of the elements of data contains 2 records, separated by a ';'). One of the records has all 3 fields, one of the records has 2 fields, and the other records each have just a single field. There are at least 3 different workers since there are 3 different ages. [BOB 22 013],[BOB 17 0234],[TOM 16 099] is one possibility that is consistent with these 5 data records.
1)
    
{"2 01;02 B;B;B 02;2 02;C   02"}
Returns: -1
One record has the employee with id 02 being named B, while another record claims that 02 is named C. So these records are inconsistent.
2)
    
{"A 21","B 21","B 23","A 23","01 A","02 21","B 03","04 B"}
Returns: 4
One way to untangle these 8 records into just 4 employees is [A 23 01], [B 21 03], [B 23 04], [A 21 02].
3)
    
{"96;DJG 00 88;EFD 88"}
Returns: 3
4)
    
{"00 BOB 22","0 BOB 22"}
Returns: 2
Id's 0 and 00 are different, so these two cannot be combined.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ShortPath

Graph Theory



Used in:

TCCC '04 Semifinals 3

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

lbackstrom , brett1479 , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2007

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5078&pm=2007

Problem Statement

    Given a starting point and a finishing point on a square grid, along with some grid points that are forbidden, determine the length of the shortest path from start to finish. In one step you may move one unit horizontally, vertically, or diagonally (but not onto a forbidden point).

Create a class ShortPath with a method steps that is given int[] x and int[] y as input. Corresponding elements of x and y give the coordinates of a point. The first elements of x and y give the start, the second elements give the finish, and additional corresponding pairs of elements from x and y specify forbidden points. Your method should return the minimum number of steps required to go from start to finish, or -1 if it is not possible to go from start to finish.

 

Definition

    
Class:ShortPath
Method:steps
Parameters:int[], int[]
Returns:int
Method signature:int steps(int[] x, int[] y)
(be sure your method is public)
    
 

Constraints

-x will have between 2 and 50 elements inclusive.
-y will have the same number of elements as x.
-Each element of x will be between -1,000,000,000 and 1,000,000,000 inclusive.
-Each element of y will be between -1,000,000,000 and 1,000,000,000 inclusive.
-The start and finish points will be distinct from each other and from all other points given by x and y.
 

Examples

0)
    
{0,2,1}
{0,2,1}
Returns: 3
   3  --|--|--|--|--|--|--
   2  --|--|--F--|--|--|--
   1  --|--X--|--|--|--|--
   0  --S--|--|--|--|--|--
        0  1  2  3  4  5
In the diagram, S is the start point, F is the finish, and X is forbidden. There are two different paths of length 3, one of which is S to (0,1) to (1,2) to F. The direct path of length 2 is blocked by the forbidden point.
1)
    
{0,1,2,2}
{0,1,2,2}
Returns: 1
Take a single diagonal step from (0,0) to (1,1). The second appearance of (2,2) on the forbidden list is legal but never matters.
2)
    
{1,100000,0,0,0,2,2,2,1,1}
{1,200000,0,1,2,0,1,2,0,2}
Returns: -1
The start point is trapped in a square of forbidden points.
3)
    
{1,100000,0,0,0,2,2,2,1}
{1,200000,0,1,2,0,1,2,0}
Returns: 199999

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PipePuzzle

Recursion, Search



Used in:

SRM 265

Used as:

Division II Level Three

Writer:

HardCoder

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2001

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8007&pm=2001

Problem Statement

    The pipe game is played on a grid with three kinds of pipes. The straight pipe '-' allows water to flow straight. The elbow pipe 'L' diverts water either to the left or to the right. The cross pipe '+' has the same effect as a straight pipe. Unlike the other two pipes, the cross pipe allows water to flow through it a second time in a direction perpendicular to the first pass. The water source is represented by one of: 'N', 'S', 'W' or 'E' indicating whether the water will begin flowing north, south, west or east respectively. You are allowed to rotate each pipe in the grid by 90 degree increments with the objective of maximizing the number of pipes connected to the water source.

Given a String[] pipes that represents the game grid, determine the length of the longest possible flow of water. Each pipe that the water flows through adds one to the total length. A cross pipe through which water passes twice contributes two to the overall length. The starting water source is not a pipe, does not count towards the length, and may not be rotated.


{"LL-L-",
 "L+L+L",
 "--NL-",
 "L+--L",
 "LL+L-"}



This is a graphical representation of the puzzle above.

 

Definition

    
Class:PipePuzzle
Method:longest
Parameters:String[]
Returns:int
Method signature:int longest(String[] pipes)
(be sure your method is public)
    
 

Notes

-In each grid, south is the direction of increasing index within pipes, and north that of decreasing index. East is the direction of increasing index within an element of pipes, and west that of decreasing index.
 

Constraints

-pipes will have between 1 and 20 elements, inclusive.
-Each element of pipes will have length between 1 and 20, inclusive.
-Every element of pipes will have the same length.
-pipes will only contain the characters ('-', 'L', '+', 'N', 'S', 'E', 'W').
-pipes will have exactly one water source.
-pipes will contain between 0 and 20 elbow 'L' pipes, inclusive.
 

Examples

0)
    
{"LL-L-",
 "L+L+L",
 "--NL-",
 "L+--L",
 "LL+L-"}
Returns: 19
1)
    
{"ELLL",
 "LLLL",
 "LLLL",
 "LLLL"}
Returns: 13
2)
    
{"ELLLLL+",
 "++++++L",
 "L+++++L",
 "L+++++L",
 "L+++++L",
 "L+++++L",
 "+LLLLLL"}
Returns: 71
3)
    
{"-+-+-+-+-+-+-+-+-+-W"}
Returns: 19
4)
    
{"N"}
Returns: 0

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FontSize

Simple Search, Iteration



Used in:

SRM 265

Used as:

Division II Level One

Writer:

HardCoder

Testers:

PabloGilberto , brett1479 , Olexiy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=2000

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8007&pm=2000

Problem Statement

    Graphical user interfaces rely on text routines to properly display words on various GUI components. Being able to determine the width in pixels of a line of text is useful for centering the text in a window. You will be given a sentence of letters and spaces. You will also be given the letter widths for both uppercase and lowercase letters of a particular font. You must return the width of the sentence.

Both uppercase and lowercase contain 26 elements. The first element of uppercase is the width of 'A' and the last is the width of 'Z'. The first element of lowercase is the width of 'a' and the last is the width of 'z'. The width of the space character is always 3 pixels. When a line of text is rendered, there is a gap of 1 pixel between each pair of adjacent characters.

 

Definition

    
Class:FontSize
Method:getPixelWidth
Parameters:String, int[], int[]
Returns:int
Method signature:int getPixelWidth(String sentence, int[] uppercase, int[] lowercase)
(be sure your method is public)
    
 

Constraints

-sentence will contain between 1 and 50 characters, inclusive.
-sentence will only contain uppercase letters ('A'-'Z'), lowercase letters ('a'-'z'), and spaces.
-uppercase will contain exactly 26 elements.
-lowercase will contain exactly 26 elements.
-Each value in uppercase and lowercase will be between 1 and 36, inclusive.
 

Examples

0)
    
"Dead Beef"
{6,6,6,7,7,7,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9}
{5,5,5,4,4,4,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9}
Returns: 49
D   e   a   d  (space)  B   e   e   f
7+1+4+1+5+1+4+1 + 3 + 1+6+1+4+1+4+1+4 = 49
1)
    
"Hello World"
{7,8,8,8,7,8,8,8,7,8,8,8,8,8,7,8,8,8,8,8,7,8,8,8,8,8}
{5,6,6,6,5,6,6,6,5,6,6,6,6,6,5,6,6,6,6,6,5,6,6,6,6,6}
Returns: 74
2)
    
"Hello World"
{7,7,7,7,7,7,7,8,7,7,7,7,7,7,7,7,7,7,7,7,7,7,9,7,7,7}
{5,5,5,6,6,5,5,5,5,5,5,1,5,5,6,5,5,6,5,5,5,5,5,5,5,5}
Returns: 63
3)
    
"ThE qUiCk BrOwN fOx JuMpEd OvEr ThE lAzY dOg"
{36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11}
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26}
Returns: 778
4)
    
"two  spaces"
{9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9}
{3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3}
Returns: 43

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PipePath

Graph Theory



Used in:

TCO '03 Semifinals 4

Used as:

Division I Level Two

Writer:

brett1479

Testers:

lbackstrom , schveiguy , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1994

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4709&pm=1994

Problem Statement

    Your company controls the flow of oil through a network of pipes. The network is composed of N waypoints, each of which has a number between 0 and N-1 inclusive. Some of the waypoints are connected by pipes. You will be given String[]s caps and costs describing these pipes. Each element of caps and costs will be formatted as follows (quotes for clarity):
	"x1,y1 x2,y2 x3,y3 ..."
Each x,y pair is called an indicator. Element i of caps will always contain the same number of indicators as element i of costs. Furthermore, the jth indicator of element i of caps will correspond to the jth indicator of element i of costs. If element i of caps contains the indicator x,y it means there is a pipe that allows y units of flow from waypoint i to waypoint x. The corresponding pair x,z in element i of costs gives the cost z attributed to using this pipe.



In this network, one waypoint has been designated as the source, and another as the sink. Your business would like to send oil from the source to the sink but it also wants to save money. For this reason, only 1 path will be activated. Your job is to find the path from the source to the sink that maximizes the ratio capacity/cost. For the purposes of this problem, a path will consist of an ordered sequence of distinct waypoints, from the source to the sink, where each consecutive pair of waypoints are connected by a pipe. The pipes on the path must allow oil to flow in the direction of the path (source to sink). No flow of oil may enter the source or leave the sink. The cost of a path is the sum of all the costs of the pipes on the path. The capacity is the minimum capacity over all the pipes on the path. Note that the pipes are directed, so you can push oil from waypoint i to waypoint j only if there is a pipe allowing such a flow in that direction. You will return the maximum value of capacity/cost accurate to 1e-9 absolute or relative. If there is no path of pipes from source to finish to push oil through, return 0.
 

Definition

    
Class:PipePath
Method:capCost
Parameters:String[], String[], int, int
Returns:double
Method signature:double capCost(String[] caps, String[] costs, int source, int sink)
(be sure your method is public)
    
 

Notes

-A pipe from waypoint i to waypoint j does not imply there is a pipe from j to i.
-There can be multiple pipes carrying oil from waypoint i to waypoint j.
 

Constraints

-caps will contain between 2 and 50 elements inclusive.
-caps and costs will contain the same number of elements.
-Each element of caps and costs will contain between 0 and 50 characters inclusive.
-Each element of caps and costs will be a single space delimited list of indicators. Each indicator will take the form (quotes for clarity) "x,y". x will have no extra leading zeros, and will be between 0 and N-1 inclusive, where N is the number of elements in caps. y will have no extra leading zeros, and will be between 1 and 20000000 inclusive.
-Element i of caps will not contain the indicator "i,y".
-Each element of caps and costs will have no leading or trailing whitespace.
-Element i of caps will have the same number of indicators as element i of costs.
-The jth indicator of element i of caps will have the same first value as the jth indicator of element i of costs.
-source and sink will be between 0 and N-1 inclusive, where N is the number of elements in caps.
-source and sink will not be equal.
 

Examples

0)
    
{"1,10 2,9","","1,100"}
{"1,100 2,50","","1,50"}
0
1
Returns: 0.1
The 2 paths from waypoint 0 to waypoint 1 have a cost of 100. Since one has capacity 9, and the other has capacity 10, we choose the capacity 10 path.
1)
    
{"1,3 3,5","3,2 2,6","3,2","1,1 2,4 4,6",
 "0,3 2,7"}
{"1,3 3,5","3,2 2,6","3,2","1,1 2,4 4,6",
 "0,3 2,7"}
0
4
Returns: 0.45454545454545453
2)
    
{"1,15 1,20","2,10",""}
{"1,10 1,10","2,15",""}
0
2
Returns: 0.4
There are multiple pipes from waypoint 0 to waypoint 1.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

T9Input

Simple Search, Iteration, String Manipulation



Used in:

TCO '03 Semifinals 1

Used as:

Division I Level One

Writer:

schveiguy

Testers:

lbackstrom , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1966

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4706&pm=1966

Problem Statement

    

With the advent of text messaging on cell phones, a new method for typing has evolved, called T9. The way T9 works is it has a dictionary of words, where each letter is mapped to a number 2-9. The number-letter mappings are fixed, and are printed on the number keys of the phone. For example, 2 corresponds to 'a', 'b', and 'c'. A word is defined as a sequence of lowercase letters. Since most words use different digits for their characters, it is possible to determine which word a user is typing by matching the digit sequence to the letter sequence. Below are all the mappings for the characters used in the problem:

2 - abc
3 - def
4 - ghi
5 - jkl
6 - mno
7 - pqrs
8 - tuv
9 - wxyz
# - <space>
0 - <next word>

So for example, to type "hello world", you would press "43556#96753". A conflict arises when two words have the same digit sequence. So for example, "the" and "tie" both have the same digit sequence - "843". The way T9 handles these conflicts is to display the word that comes first alphabetically. Then, if the word isn't desired, the user must press 0 to get the next word alphabetically, and repeat until the desired word is shown. If the user wishes to enter another word, he/she presses # to insert a space and starts entering the next word. So to input "the tie", you would type "843#8430". It is illegal to press a non-zero digit immediately after pressing '0', the only legal keys you can press after pressing '0' are '0' and '#'.

You will be given a String[] messages, which consists of messages you are to type into your cell phone. messages will only contain spaces and words made entirely of lowercase letters. Assume that the words contained in all of the messages are exactly the words contained in the T9 dictionary. Return a String[] where each element i contains the numeric keypresses you would have to type for element i of messages. Note that messages do not necessarily have to contain words, and can contain sequences of multiple spaces which must be preserved.

 

Definition

    
Class:T9Input
Method:getKeypresses
Parameters:String[]
Returns:String[]
Method signature:String[] getKeypresses(String[] messages)
(be sure your method is public)
    
 

Constraints

-messages will have between 1 and 50 elements, inclusive.
-Each element of messages will have between 0 and 50 characters, inclusive.
-Each element of messages will contain only lowercase letters ('a'-'z') and spaces.
-There will not be more than 7 words which have the same digit sequence.
 

Examples

0)
    
{"the tie", "the tie"}
Returns: { "843#8430",  "843#8430" }
The example from the problem statement.
1)
    
{" hey joe   ", "   "}
Returns: { "#439#563###",  "###" }
Don't forget to preserve multiple spaces, and to handle messages where there are no words.
2)
    
{"cba cba cba cba cba cba cba cba", "abc acb bac bca cab cba"}
Returns: 
{ "22200000#22200000#22200000#22200000#22200000#22200000#22200000#22200000",
 "222#2220#22200#222000#2220000#22200000" }
Remember that the dictionary contains all words from all the messages, not just the message you are working on.
3)
    
{ "the longest case for t nine is probably when",
  "you enter seven two letter sequences from the",
  "same key and then repeat the alphabetically",
  "last case over and over again for the entire",
  "list of messages",
  "",
  "these paragraphs demonstrate how efficient t",
  "nine is since there is only one time where you",
  "must use the zero key"}
Returns: 
{ "843#5664378#2273#367#8#6463#47#77622259#9436",
 "968#36837#73836#896#538837#737836237#3766#843",
 "7263#539#263#8436#737328#843#25742238422559",
 "5278#2273#6837#263#6837#24246#367#843#368473",
 "5478#63#63772437",
 "",
 "843730#7272472747#33666787283#469#333424368#8",
 "6463#47#74623#84373#47#6659#663#8463#94373#968",
 "6878#873#843#9376#539" }
4)
    
{"cca ccc c cccb ccca cccc"}
Returns: { "222#2220#2#22220#2222#222200" }
Note that to make "cccc", you cannot use "22202". Pressing '2' after pressing '0' is illegal.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

AlgoHill

Graph Theory, Search



Used in:

CRPF Charity Finals

Used as:

Division I Level Two

Writer:

chogyonim

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1946

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4664&pm=1946

Problem Statement

    

Given a map of a hill, there are many ways for an agent to get from one point to another point. Many different algorithms have been developed to find the best, or reasonably good ways to get from a starting location to an ending location. One such method is the breadth-first-search (BFS) algorithm, where the agent always expands the location with the least accumulated cost. Another method is called A*, which involves predicting the total cost to the goal based on the cost so far, and a heuristic which calculates the expected cost to come, and then expanding the nodes in a BFS-fashion based on this expected, rather than already accumulated, cost.

When a search method expands a node, it assigns a new cost to each neighbor, unless that neighbor already has an equal or lesser cost assigned. In BFS, this cost is the cost to get to the current node plus the cost of moving from the current node to the given neighboring node. In A*, this is the total cost as in BFS plus the predicted cost based on the heuristic function. The search ends when the goal node is expanded, and not when its cost is calculated. This is because different neighboring nodes can assign different costs to the goal, so terminating before the goal node itself is expanded can give a sub-optimal solution. Once the goal is expanded, however, you are guaranteed that no neighbor will assign it a lower cost than the one it currently has, and thus it is optimal.

BFS (for reference): For BFS, the agent starts at the starting location (hereafter referred to as S) with a cost of 0. The agent expands this location (also referred to as a node), calculating the cost for all of its neighbors. It then expands all nodes with a calculated cost of 1, then all nodes with a calculated cost of 2, and so forth, until it has expanded the goal node. Notice that a given node may be assigned different costs by different neighbors, but this is okay because we assume that the cost is always increasing, so it should be assigned the lowest cost possible and expanded in turn.

A*: For A*, the agent starts at S, with a so-far cost of 0. The heuristic function our agent uses will be the "Manhattan Distance" from the current node to the goal node (hereafter referred to as G), that is, the positive difference in X values plus the positive difference in Y values. The agent expands S, assigning all of its neighbors a cost as with BFS, but with an additional predicted cost (the Manhattan Distance to the goal). It then expands the nodes in a BFS-fashion using these total predicted costs. A* should NOT expand a node that it has already expanded previously.

For this problem, the agent can move across the hill in any of the four cardinal directions (north, east, west and south.) The cost of moving down the hill is 1, of moving across a plateau (between 2 squares of equal altitude) is 2, and of moving up the hill is 3. The hill is represented by a String[] hill, which represents the altitudes as 1 through 9 (with 9 being the highest altitude). The x and y coordinates of S and G are represented respectively by int sx sy gx and gy. The y coordinate is the 0-indexed element in hill, and the x coordinate is the 0-indexed location in the element of hill. Use the A* method to search for G starting from S, and return the number of nodes expanded. Expand all nodes that share the same predicted cost as G. For example, if you expand G with a predicted cost of 10, make sure that all other nodes with a predicted cost of 10 are also expanded, to avoid ambiguities.

 

Definition

    
Class:AlgoHill
Method:astar
Parameters:String[], int, int, int, int
Returns:int
Method signature:int astar(String[] hill, int sx, int sy, int gx, int gy)
(be sure your method is public)
    
 

Constraints

-hill will contain between 5 and 50 elements, inclusive.
-each element of hill will have between 5 and 50 characters, inclusive.
-each element of hill will have the same number of characters as every other element of hill.
-each element of hill will contain only the characters '1' through '9'.
-sy and gy will each be between 0 and one less than the number of elements in hill, inclusive.
-sx and gx will each be between 0 and one less than the length of the elements in hill, inclusive.
 

Examples

0)
    
{"34567",
 "23456",
 "12345",
 "23456",
 "34567"}
0
2
2
2
Returns: 5

A* will assign the following costs:

10 *  *  *  *
6  8  10 *  *
2  4  6  10 *
6  8  10 *  *
10 *  *  *  *

All nodes with a predicted cost less than or equal to 6 will be expanded (5 nodes).

1)
    
{"55555",
 "54555",
 "55355",
 "55525",
 "55551"}
0
0
4
4
Returns: 25
In this case, A* expands all nodes. Also, note that several times in this example, a node of cost C expands to form another node with cost C, and this new node must also be expanded before going on to expand nodes of cost greater than C.
2)
    
{"55555",
 "54445",
 "54345",
 "54445",
 "55555"}
0
1
4
3
Returns: 21
3)
    
{"99999",
 "89992",
 "76543",
 "99992",
 "99991"}
0
0
4
0
Returns: 13
Note that the node at (4,1) gets expanded by A*. Prior to expanding nodes with a predicted cost of 8, this node has no cost. After expanding the node at (4,2), this is assigned a predicted cost of 8 (the same as the goal) and therefore should be expanded.
4)
    
{"68233335836531",
 "57244363483169",
 "92744511826738",
 "76864574378195",
 "39927887799237",
 "89447973623642",
 "19758793475135",
 "33857155647757",
 "82987352116383",
 "18813823791825",
 "91772225881964",
 "46692256258431",
 "41961397519198",
 "48265328441524",
 "31422961925492",
 "17844758382392",
 "47549368526297",
 "27955796939522",
 "59699922792416",
 "56366572279148",
 "26884644728715",
 "98234493558879",
 "38984599399327",
 "66812381124583",
 "73833939626911",
 "13681831986111",
 "69237772565286",
 "34347792857462"}
8
2
8
2
Returns: 1
The start node is the goal node, and is the only node that you expand.
5)
    
{"44435",
 "44425",
 "44445",
 "32445",
 "55555"}
0
0
2
2
Returns: 13

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

UndergroundVault

Graph Theory



Used in:

SRM 171

Used as:

Division I Level Three

Writer:

Running Wild

Testers:

lbackstrom , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1939

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4660&pm=1939

Problem Statement

    You work for a company that stores its goods in a large underground vault. There have been flood warnings, and it may be necessary to seal the vault to protect it from flood waters. The vault is a series of rooms that are connected by doors, each of which can only be sealed from one of the rooms it connects. To ensure that the rooms are as safe as possible, you want to seal every individual door in the vault. You can't do this, however, just by sealing any door you see, because you could close off a section of the vault and be unable to seal doors in that section, or you could seal yourself in the vault!



You begin (and must end) in room 0. When you seal a room, you close all doors in that room that must be sealed from that side. If there are other doors that go to that room that must be sealed from the other side, they remain open (but the room is still considered sealed). Given a String[], rooms, describing the vault, return a int[] that gives the order in which to seal the rooms. If there exist multiple solutions, return the one that is lexicographically first. When ordered lexicographically, int[] A comes before int[] B if and only if for the smallest i such that A[i]!=B[i], A[i]<B[i]. Keep in mind that every room must be sealed, even though in some cases sealing a room does not close any doors.



Each element of rooms will be a comma delimited list of numbers. The i-th element of rooms will list all rooms adjacent to room i that must be sealed from room i. For any two rooms i and j, there will be at most one door connecting them. If there is a door connecting them, i will be listed as adjacent to j, or vice versa, but not both.
 

Definition

    
Class:UndergroundVault
Method:sealOrder
Parameters:String[]
Returns:int[]
Method signature:int[] sealOrder(String[] rooms)
(be sure your method is public)
    
 

Notes

-There can be cycles. For example: room i has a door to room j that must be sealed from room i, room j has a door to room k that must be sealed from room j, and room k has a door to room i that must be sealed from room k.
 

Constraints

-rooms will contain between 1 and 50 elements, inclusive.
-Each element of rooms will contain only the digits '0'-'9' and commas.
-Each element of rooms will only contain values between 0 and the number of elements in rooms - 1, inclusive, and no value will have leading zeros.
-No element of rooms will contain leading or trailing commas, or more than one commma between values.
-Element i of rooms will not contain the value i.
-No element of rooms will contain the same value more than once.
-If element i of rooms contains j, element j of rooms will not contain i.
-There will be a way to seal all the rooms and end in room 0.
 

Examples

0)
    
{"1","2",""}
Returns: { 2,  1,  0 }
We can't seal room 0 first, because then we won't be able to reach any other rooms.

We can't seal room 1 first either because then we can't reach room 2 to seal it.

The only way is to seal room 2, then 1, then finally 0.
1)
    
{"1","2","3","1"}
Returns: { 3,  2,  1,  0 }
Rooms 1, 2, and 3 form a cycle. Each one must seal a door to the next one

in the cycle. The only way to seal all the rooms is to go to room 3, seal it,

and then work backwards through the cycle.
2)
    
{"3,5","2","8","","","6,7","","1,8","4"}
Returns: { 2,  1,  3,  4,  6,  8,  7,  5,  0 }
3)
    
{"1,2","3","3,5","4","",""}
Returns: { 1,  4,  3,  5,  2,  0 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RoomSummary

String Manipulation, String Parsing



Used in:

CRPF Charity Round 1

Used as:

Division I Level Two

Writer:

Wernie

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1935

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4656&pm=1935

Problem Statement

    Given a summary of events occurring during a TopCoder match in a single room, return the room summary for that room. The room summary is a list of coders' handles with their point totals, sorted in decreasing order by points. Ties are broken by listing lexicographically lower handles first (according to ASCII values).

The room summary is a String[], where each element is the result of a coder's performance in the format "<handle> <points>" (quotes for clarity) where <handle> is the coder's handle and <points> is the coder's point total (<points> must contain exactly 2 decimal places and have no extra leading zeros), eg. "SnapDragon 1201.30"



The Problems



The name of the three problems are given in the String[] problems.



The Coders



The coder's handles are given in the String[] handles.



I. Coding Phase



Each event during the Coding Phase is a submission, which is given as an element of the String[] submissions in the following format:

"<handle> <problem> <points>" (quotes for clarity), where
  • <handle> is a coder's handle that corresponds to an element of handles,
  • <problem> is a problem's name that corresponds to an element of problems,
  • <points> is the points the coder receives for the submission of the respective problem, with exactly 2 decimal places and no extra leading zeros, eg. "612.34" (quotes for clarity).
This means that coder <handle> submits problem <problem> for <points> points. If a coder submits a problem more than once (i.e. resubmits), only the last submission made (i.e. the one with the higher index in submissions) is to be considered. Points are between 60.00 and 1000.00, inclusive.



II. Challenge Phase



Each event during the Challenge Phase is a challenge, which is given as an element of challenges in the following format:

"<handle1> <handle2> <problem> <result>" (quotes for clarity), where
  • <handle1> is a coder's handle that corresponds to an element of handles,
  • <handle2> is a coder's handle that corresponds to a different element of handles,
  • <problem> is a problem's name that corresponds to an element of problems,
  • <result> is the result of the challenge, either "successful" or "unsuccessful" (quotes for clarity).
This means that coder <handle1> challenges problem <problem> of coder <handle2> with the result <result>. For a successful challenge, <handle1> receives 50 points and <handle2> loses all points for his submission of <problem>. For an unsuccessful challenge, <handle1> loses 50 points (possibly getting a negative score). Challenges occur in the order listed in challenges. Coders with a non-positive score are still allowed to challenge (unlike in real TopCoder matches).



III. System Testing Phase



Each element in failed is a result of the System Testing Phase in the following format:

"<handle> <problem>" (quotes for clarity), where
  • <handle> is a coder's handle that corresponds to an element of handles,
  • <problem> is a problem's name that corresponds to an element of problems.
This means that problem <problem> of coder <handle> failed the system tests and <handle> loses all points for his submission of <problem>. All submissions that pass the system tests are not listed within failed.
 

Definition

    
Class:RoomSummary
Method:generate
Parameters:String[], String[], String[], String[], String[]
Returns:String[]
Method signature:String[] generate(String[] problems, String[] handles, String[] submissions, String[] challenges, String[] failed)
(be sure your method is public)
    
 

Notes

-Problem names and coder handles are case sensitive.
 

Constraints

-problems contains exactly 3 elements.
-Each element of problems contains between 1 and 15 alphanumeric characters ('A'-'Z', 'a'-'z', '0'-'9').
-There are no duplicates within problems.
-handles contains between 1 and 20 elements, inclusive.
-Each element of handles contains between 1 and 10 alphanumeric characters ('A'-'Z', 'a'-'z', '0'-'9').
-There are no duplicates within handles.
-submissions contains between 0 and 50 elements, inclusive.
-challenges contains between 0 and 50 elements, inclusive.
-failed contains between 0 and 50 elements, inclusive.
-All elements of submissions, challenges and failed are formatted as described in the problem statement.
-Points for submissions are between 60.00 and 1000.00, inclusive.
-A resubmission results in a lower score than a previous submission or in the minimal possible score of 60.00.
-A coder will not challenge his own problems or another coder's problem that was previously unsuccessfully challenged by him or successfully challenged by somebody else. Only problems that have been submitted will be challenged.
-failed only contains problems that have been submitted and have not been successfully challenged.
 

Examples

0)
    
{ "EasyP", "MediumP", "HardP" }
{ "Andrea", "Billy", "Chris", "eddy", "David", "Feliza" }
{ "Andrea EasyP 220.31",
  "Billy EasyP 213.24",
  "Chris EasyP 194.24",
  "Chris EasyP 75.00",
  "Andrea MediumP 472.23",
  "Billy MediumP 428.34",
  "Andrea HardP 823.60" }
{ "Chris Andrea EasyP unsuccessful",
  "Chris Billy EasyP unsuccessful",
  "Billy Andrea HardP successful" }
{ "Billy MediumP" }
Returns: 
{ "Andrea 692.54",
 "Billy 263.24",
 "David 0.00",
 "Feliza 0.00",
 "eddy 0.00",
 "Chris -25.00" }
Andrea has 1516.14 (220.31 + 472.23 + 823.60) points after the coding phase. She loses 823.60 points during the challenge phase because her submission of HardP was successfully challenged. Her final score is 692.54.

Billy has 641.58 (213.24 + 428.34) points after the coding phase. He gains 50.00 points during the challenge phase and loses 428.34 points because his MediumP fails the system tests. His final score is 263.24.

Chris receives 75.00 points for his submission of EasyP (which was a resubmission), but loses 100.00 points due to two unsuccessful challenges. His final score is -25.00.

David, eddy and Feliza are not involved in any submission or challenge, thus all have a final score of 0.00. They are listed in lexicographical order (lower ASCII values first).
1)
    
{ "EasyP", "MediumP", "HardP" }
{ "Andrea", "Billy", "Chris" }
{ "Billy EasyP 240.31",
  "Billy MediumP 425.23",
  "Chris HardP 831.42",
  "Andrea EasyP 89.12" }
{ "Andrea Billy EasyP unsuccessful",
  "Andrea Chris HardP unsuccessful" }
{}
Returns: { "Chris 831.42",  "Billy 665.54",  "Andrea -10.88" }
2)
    
{ "250pointer", "500pointer", "1000pointer" }
{ "Andrea", "Billy", "Chrissy", "Chris" }
{ "Billy 250pointer 244.32",
  "Andrea 250pointer 241.42",
  "Andrea 500pointer 432.39",
  "Billy 500pointer 372.40",
  "Billy 250pointer 100.42" }
{ "Billy Andrea 250pointer unsuccessful",
  "Andrea Billy 500pointer successful",
  "Billy Andrea 500pointer unsuccessful" }
{}
Returns: { "Andrea 723.81",  "Billy 0.42",  "Chris 0.00",  "Chrissy 0.00" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WhichData

Brute Force, Math



Used in:

TCO '03 Round 4

Used as:

Division I Level One

Writer:

brett1479

Testers:

lbackstrom , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1933

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4705&pm=1933

Problem Statement

    You have just received a int[] sampleData from the laboratory. You know that the variance of this data should be varNum/varDen, where varNum and varDen are ints. Note that varNum/varDen need not be an integer. Your method will return which nonempty subset of the elements from sampleData produces a variance closest to the variance you expected. This subset may be the entire sampleData. The variance of a subset of the sampleData can be calculated via the following formula. Let s(i) denote the ith element of the subset (assuming some method of indexing into the subset), and let n denote the size of the subset. Then
     mean = ( s(0) + s(1) + s(2) + ... + s(n-1) )/n
     varsum = (mean-s(0))^2 + (mean-s(1))^2 + ... + (mean-s(n-1))^2
     variance = varsum/n
The subset will be returned as a int[], whose elements are the values of the subset, sorted in nondescending order. If two subsets are equally far from the expected variance, choose the one whose return value comes first lexicographically. A int[] X comes lexicographically before a int[] Y if there is a position j such that, X[i]=Y[i] for all i<j, and X[j]<Y[j]. If X is a proper prefix of Y, it occurs lexicographically before it.
 

Definition

    
Class:WhichData
Method:bestVariance
Parameters:int[], int, int
Returns:int[]
Method signature:int[] bestVariance(int[] sampleData, int varNum, int varDen)
(be sure your method is public)
    
 

Notes

-doubles will provide enough precision to properly solve this problem. Given two subsets, s1 and s2, the difference between |variance(s1)-varNum/varDen| and |variance(s2)-varNum/varDen| will be either 0, or greater than 1e-9, where variance(x) is the variance of subset x.
 

Constraints

-varNum will be between 0 and 10000 inclusive.
-varDen will be between 1 and 10000 inclusive.
-sampleData will contain between 2 and 16 elements inclusive.
-Each element of sampleData will be between -10000 and 10000 inclusive.
 

Examples

0)
    
{1,2,3,4,5,6,7,8}
40
20
Returns: { 1,  2,  3,  4,  5 }
The variance should be 40/20 = 2. The set of numbers {1,2,3,4,5} has
	mean = (1+2+3+4+5)/5 = 3
	varsum = 2^2 + 1^2 + 0^2 + 1^2 + 2^2 = 10
	variance = 10/5 = 2
1)
    
{1,2,3,4,5,6,7,8}
6
1
Returns: { 1,  2,  4,  5,  8 }
2)
    
{-10000,10000,-9999,9999,-9998,9000}
10000
1
Returns: { -10000,  -9998 }
3)
    
{-10000,10000,-9999,9999,-9998,9998,1,1,2,2}
9999
10000
Returns: { -10000,  -9998 }
4)
    
{500,500,500,500,500,500,500,580,
 100,100,100,100,100,100,100,180}
700
1
Returns: { 100,  100,  100,  100,  100,  100,  100,  180 }
5)
    
{10,10,10,10,10,10}
0
9999
Returns: { 10 }
6)
    
{2,5,8,15,-14,0,-2,3,0,-10,-3,-9,6,-13,4,-1}
5787
170
Returns: { -14,  -10,  -3,  -1,  0,  0,  2,  3,  4,  5 }
7)
    
{-14,-3,-1,10,-5,0,13,6,11,9,5,6,3,-2,0,2}
5061
225
Returns: { -5,  -3,  -2,  -1,  0,  2,  5,  6,  6,  11 }
8)
    
{0,-13,15,5,5,-7,-6,-7,-8,4,-12,-13,14,9,-3,-1}
9262
197
Returns: { -13,  -13,  -12,  -7,  -7,  -6,  -3,  4,  5,  5 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RookAttack

Graph Theory



Used in:

TCO '03 Semifinals 4

Used as:

Division I Level Three

Writer:

brett1479

Testers:

lbackstrom , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1931

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4709&pm=1931

Problem Statement

    You have been given a rows-by-cols chessboard, with a list of squares cut out. The list of cutouts will be given in a String[] cutouts. Each element of cutouts is a comma-delimited lists of coords. Each coord has the form (quotes for clarity) "r c". If coord "r c" appears in an element of cutouts, it means that the square at row r column c (0-based) has been removed from the chessboard. This problem will involve placing rooks on a chessboard, so that they cannot attack each other. For a rook to attack a target piece, it must share the same row or column as the target. Your method will return an int that will be the maximum number of rooks that can be placed on the chessboard, such that no pair of rooks can attack each other. Rooks cannot be placed on cut out squares. The cut out squares do not affect where the rooks can attack.
 

Definition

    
Class:RookAttack
Method:howMany
Parameters:int, int, String[]
Returns:int
Method signature:int howMany(int rows, int cols, String[] cutouts)
(be sure your method is public)
    
 

Constraints

-rows will be between 1 and 300 inclusive.
-cols will be between 1 and 300 inclusive.
-cutouts will contain between 0 and 50 elements inclusive.
-Each element of cutouts will contain between 3 and 50 characters inclusive.
-Each element of cutouts will be a comma delimited list of coords. Each coord will be of the form "r c", where
  • r and c are integers, with no extra leading zeros,
  • r is between 0 and rows-1 inclusive,
  • and c is between 0 and cols-1 inclusive.
-Each element of cutouts will not contain leading or trailing spaces.
 

Examples

0)
    
8
8
{}
Returns: 8
........ 
........ 
........ 
........ 
........ 
........ 
........ 
........
1)
    
2
2
{"0 0","0 1","1 1","1 0"}
Returns: 0
XX 
XX  
2)
    
3
3
{"0 0","1 0","1 1","2 0","2 1","2 2"}
Returns: 2
X.. 
XX. 
XXX
3)
    
3
3
{"0 0","1 2","2 2"}
Returns: 3
X.. 
..X 
..X
4)
    
200
200
{}
Returns: 200

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MakeUnique

Dynamic Programming, String Manipulation



Used in:

TCO '03 Semifinals 3

Used as:

Division I Level One

Writer:

dgoodman

Testers:

lbackstrom , schveiguy , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1905

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4708&pm=1905

Problem Statement

    Given a sequence of uppercase letters, we want to remove all but one occurrence of each letter, doing it in such a way that the remaining letters are in alphabetical order. Of course, there may be no way to do this, but if there is, we want to know which letters to remove.

Create a class MakeUnique that contains a method eliminated that is given a String original, and returns original with the eliminated letters replaced with periods ('.'). The remaining letters must be in alphabetical order.

If there is no way to do this, return a String with length 0.

If there are several ways to do this, choose the one with the shortest length between the first and last remaining letters. If there are still several ways, return the String among these that comes earliest lexicographically ('.' comes earlier than any letter in the ASCII sequence).

 

Definition

    
Class:MakeUnique
Method:eliminated
Parameters:String
Returns:String
Method signature:String eliminated(String original)
(be sure your method is public)
    
 

Constraints

-original will contain between 1 and 50 characters inclusive
-each character in original will be an uppercase letter 'A'-'Z'
 

Examples

0)
    
"ABBBXCXABCX"
Returns: ".......ABCX"
The 4 letters ABCX must remain, and in that order. "AB...CX...." would also leave these letters in the appropriate order, but the length between the first and last remaining letters would be longer than in the given answer.
1)
    
"ABBBXCXABCB"
Returns: "A..B.CX...."
"AB...CX...." and "A.B..CX...." are also possible and have the same length between first and last remaining letters, but they come later lexicographically than the given answer.
2)
    
"ABBBXCABCB"
Returns: ""
There is no way to eliminate letters and end up with C before X.
3)
    
"AABACBXABX"
Returns: ".AB.C.X..."
4)
    
"CABDEAFDEGSDABCDEADFGSEFBGS"
Returns: "............ABCDE..FGS....."
5)
    
"AAAAAA"
Returns: ".....A"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BitmapToGraph

Simulation, String Parsing



Used in:

TCO '03 Qual. Round 2

Used as:

Division I Level Three

Writer:

lars2520

Testers:

brett1479 , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1882

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4701&pm=1882

Problem Statement

    Graphs are relatively common data structures in computer science. To visualize a graph, we often display it as a bitmap like this one:





However, an image is not very easy to work with for most purposes. It is usually much easier to perform common tasks (like finding a shortest path) if the graph is represented as a set of nodes and edges. In this problem, you will be given a graph as a bitmap, and are to convert it to a set of nodes and edges.



You have some information about the bitmap to make this task easier. First, you know that all nodes in the graph are represented by a single pixel of a certain color, which will be represented by an 'N' in the input. Furthermore, each edge will be a single color, represented by an 'E' in the input. The rest of the pixels will be represented by '.'s. After examining the images, you've come up with the following sketch for an algorithm to find and follow edges:
  1. First, find an 'N' that is adjacent to an 'E' (either orthogonally, or diagonally).
  2. Start following the edge in the same direction as you went to get from the 'N' to the 'E'.
  3. Then, as long as the edge has not terminated at an 'N', follow the edge ('E' pixels) by either continuing in the same direction, or if you cannot continue straight, by turning 45 degrees and continuing. You should always go straight when possible, but if you cannot go straight, you will be able to go either 45 degrees left, or 45 degrees right, though not both. In other words, if you cannot go straight, it will be unambiguous which way to turn (this is ensured by the constraints).
  4. If, at any point, there is an 'N' straight ahead, or there is not an edge straight ahead and there is an 'N' 45 degrees off from straight ahead, then the edge you are following terminates at that node. Again, this will not be ambiguous, so if there is neither an 'E' nor an 'N' straight ahead, then exactly one of the pixels 45 degrees off from straight will be 'N' or 'E'.
Your task is to write a method parse, which takes a String[], bitmap, each of whose elements represents a row in the bitmap, and returns a String[], each of whose elements represents a single node. To do this, you should first number all of the nodes, starting with the most upper most nodes, and breaking ties by doing the left most first. Your numbering should start at 0. Then, the ith element of the return should be a comma delimited list of all the <edge>s coming out of the ith node. Each <edge> should be formatted as <dest>:<length>, where <dest> is the number of the node to which this edge connects, and <length> is the number of 'E's in the edge. The list of edges in each element should be sorted in ascending order by the index of the element they connect to. Ties should be broken by sorting the edges in ascending order by length.
 

Definition

    
Class:BitmapToGraph
Method:parse
Parameters:String[]
Returns:String[]
Method signature:String[] parse(String[] bitmap)
(be sure your method is public)
    
 

Notes

-Only list individual loops (edges from a node to itself) once. See example 4.
 

Constraints

-bitmap will contain between 1 and 50 elements, inclusive.
-Each element of bitmap will contain the same number of characters.
-Each element of bitmap will contain between 1 and 50 characters, inclusive.
-Each character of bitmap will be an 'E', an 'N', or a '.'.
-If you follow each edge as described in the problem statement, each edge will terminate at a node.
-There will not be two adjacent 'N's.
-All of the edges will be traversed in the same manner in both directions. In other words, if there is an edge from node i to node j, there will also be an edge from node j to node i which uses all of the same pixels.
-There will be no ambiguity as to which way to go when a 45 turn must be made.
 

Examples

0)
    
   {"NEEE.....N",
    "....EEEEE.",
    ".........."}
Returns: { "1:8",  "0:8" }
The upper left 'N' is node 0, and the upper right 'N' is node 1. There is an edge with 8 'E's connecting them, so element 0 of the return is "1:8" since the edge from 0 to 1 is of length 8. Similarly, element 1 of the return is "0:8"
1)
    
    {"N.N",
     ".E.",
     "N.N"}
Returns: { "3:1",  "2:1",  "1:1",  "0:1" }
The numbers of the nodes are as follows:
    0.1
    ...
    2.3
Thus, 0 is connected to 3, and 1 is connected to 2.
2)
    
   {"N..N..N",
    ".E.E.E.",
    "..EEE..",
    "NEEEEEN",
    "..EEE..",
    ".E.E.E.",
    "N..N..N"}
Returns: { "7:5",  "6:5",  "5:5",  "4:5",  "3:5",  "2:5",  "1:5",  "0:5" }
3)
    
   {".NE....NE..N",
    "E..E...E.E..",
    "E..E...E.E.E",
    ".EE....NE..E"}
Returns: { "0:7",  "3:2,3:4",  "",  "1:2,1:4" }
Notice that the loop from node 0 to itself is only listed once. Also note that when there are multiple edges from one node to another, they are sorted by length. Finally, note that there may be edge pixels that are not part of any edge.
4)
    
{".EE....",
 "E..E...",
 "E..E...",
 "NEEEEE.",
 "...E..E",
 "...E..E",
 "...E..E",
 "....EE."}
Returns: { "0:20" }
5)
    
{".EE.",
 "N..N",
 ".EE."}
Returns: { "1:2,1:2",  "0:2,0:2" }
6)
    
   {"N..N.........",
    ".E.E.........",
    "..EE....EN...",
    "...E.N.E.....",
    "...NEEEEEN...",
    "...E.N.E.....",
    "..EE....EN...",
    ".E.E.........",
    "N..N........."}
Returns: 
{ "6:4",
 "4:3",
 "6:3",
 "6:1,7:3,8:4",
 "1:3,5:5,9:3",
 "4:5",
 "0:4,2:3,3:1",
 "3:3",
 "3:4",
 "4:3" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Scheduling

Brute Force, Recursion, Search



Used in:

SRM 165

Used as:

Division I Level Three

Writer:

lars2520

Testers:

lbackstrom , brett1479 , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1879

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4630&pm=1879

Problem Statement

    Often, a large task can be broken down into a number of smaller tasks, some of which are dependent on others. For example, developing a substantial piece of software might be broken down into 4 tasks: the database component, the server component, the client component, and integration of the three components. Each component can be written independently, but the final task of integrating the three components cannot be started until each of the components is finished.



We can think of these dependencies as a directed acyclic graph (DAG), where each node represents a task, and each directed edge represents a dependency. For example, the following graph represents the above example:
     DB------>--\
                 \
     Server------>Integration
                 /
     Client-->--/
Your task is to determine how fast some set of tasks can be completed, given that you can work on at most 2 tasks at a time, and once you start working on a task, you must work on that task until it is finished. You are to write a method, fastest, which will take a DAG representing the dependencies of the tasks and the amount of time that each task takes to complete, and should return the smallest amount of time in which every task may be finished.



The DAG will be given to you as a String[], dag. Each element of dag will be formatted as "<time>:<d0>,<d1>,...", where each <di> indicates that the task represented by this element of dag is dependent on the task represented by the dith element of dag.
 

Definition

    
Class:Scheduling
Method:fastest
Parameters:String[]
Returns:int
Method signature:int fastest(String[] dag)
(be sure your method is public)
    
 

Constraints

-dag will contain between 1 and 12 elements, inclusive.
-Each element of dag will be formatted as "<time>:<d0>,<d1>,...", where each <di> is between 0 and the number of elements in dag-1, inclusive (with no extra leading 0's anywhere).
-Each <time> will be between 1 and 10, inclusive.
-No element of dag will contain more than one occurrence of the same <di>.
-Each element of dag will contain between 2 and 50 characters, inclusive.
-dag will represent a directed acyclic graph.
 

Examples

0)
    
{"3:","2:","4:","7:0,1,2"}
Returns: 12
This represents the following DAG (numbers represent the time it takes to complete a task represented by a node).
     3-->--\
            \
     2------->7
            /
     4-->--/
This is similar to the example in the problem statement. Task 3 may not be started until tasks 0, 1, and 2 are all completed. So, the best way to do this is to start by doing both tasks 0 and 2. Then, at time 3, task 0 is completed, and you can start working on task 1. At time 4, you complete task 2, but there is nothing more to do, so at that point you are only working on one task. Then, at time 5, task 1 completes, and you can work on task 3, which completes at time 12.



Here is a table showing a timeline for one of the best ways to do it:
      | Tasks being 
 Time | worked on or
      | started
------+------
  0   | 0,2
  3   | 1,2
  4   | 1
  5   | 3
  12  | done
1)
    
{"9:","8:","6:","4:","7:","7:0,1,2,3,4","3:2,3"}
Returns: 24
This one is a little more complicated. It represents the following DAG (plugin users - please view the image in the applet):

2)
    
{ "10:", "5:", "5:1", "5:1", "5:2,3" }
Returns: 20
3)
    
{"1:","2:","4:","8:","6:","3:","7:","5:","9:","5:","10:","3:"}
Returns: 32

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Twain

String Manipulation



Used in:

SRM 169

Used as:

Division II Level Two

Writer:

huntergt

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1876

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4650&pm=1876

Problem Statement

    Spelling in the English language doesn't make sense. Congress has enacted a plan for orthographical reform (loosely based on Mark Twain's plan for the improvement of English spelling) which will change the spelling of words in the English language gradually over the next 7 years. The plan is as follows:



Year 1:
  1. - If a word starts with "x", replace the "x" with a "z".
  2. - Change all remaining "x"s to "ks"s.
Year 2:
  1. - Change all "y"s to "i"s.
Year 3:
  1. - If a "c" is directly followed by an "e" or "i", change the "c" to an "s".
Year 4:
  1. - If a "c" is directly followed by a "k", remove the "c". Keep applying this rule as necessary (Example: "cck" becomes "k".)
Year 5:
  1. - If a word starts with "sch", change the "sch" to a "sk".
  2. - If a "ch" is directly followed by an "r", change the "ch" to a "k".
  3. - After applying the above rules, change all "c"s that are not directly followed by an "h", to a "k". (This includes all "c"s that are the last letter of a word.)
Year 6:
  1. - If a word starts with "kn" change the "kn" to an "n".
Year 7:
  1. - Change all double consonants of the same letter to a single consonant. A consonant is any letter that is not one of "a, e, i, o, u." (Example: "apple" becomes "aple"). Keep applying this rule as necessary (Example: "zzz" becomes "z".)


The plan requires that rules for each year are followed in the order they are presented, and changes for each year occur after all the changes from previous years.



Write a class Twain, which contains a method getNewSpelling. getNewSpelling takes as parameters an int year representing the number of years that have passed since the plan to improve the English language began, and a String phrase representing the English phrase to convert. For the purposes of the plan, a word is a sequence of lowercase letters ('a'-'z') bounded by spaces or the start/end of phrase. The method returns a String representing the converted phrase.

 

Definition

    
Class:Twain
Method:getNewSpelling
Parameters:int, String
Returns:String
Method signature:String getNewSpelling(int year, String phrase)
(be sure your method is public)
    
 

Constraints

-year will be between 0 and 7, inclusive
-phrase will be between 0 and 50 characters, inclusive
-phrase will contain only lowercase letters ('a'-'z') and spaces (' ').
-phrase will not contain three or more of the same consonant in a row
 

Examples

0)
    
1
"i fixed the chrome xerox by the cyclical church"
Returns: "i fiksed the chrome zeroks by the cyclical church"
In year 1, the first "x" in "xerox" is changed to a "z". Then, the "x"s in "fixed" and "zerox" are changed to "ks"s.
1)
    
2
"i fixed the chrome xerox by the cyclical church"
Returns: "i fiksed the chrome zeroks bi the ciclical church"
In year 2, the "y"s in "by" and "cyclical" are changed to "i"s.
2)
    
0
"this is unchanged"
Returns: "this is unchanged"
Since the year is 0, no changes occur.
3)
    
7
"sch kn x xschrx cknnchc cyck xxceci"
Returns: "sk n z zskrks nchk sik zksesi"
In year 1, the phrase becomes "sch kn z zschrks cknnchc cyck zksceci" due to rules concerning the letter "x". In year 2, all "y"s are changed to "i"s yielding "sch kn z zschrks cknnchc cick zksceci". In year 3, "ce" and "ci" are changed to "se" and "si" yielding "sch kn z zschrks cknnchc sick zkssesi". In year 4, "ck" is changed to "k" and the phrase becomes "sch kn z zschrks knnchc sik zkssesi". In year 5, words that begin with "sch" are made to begin with "sk", "chr" is changed to "kr", and all "c"s not followed by an "h" are changed to "k" yielding "sk kn z zskrks knnchk sik zkssesi". In year 6, words that start with "kn" now start with "n" and the phrase becomes "sk n z zskrks nnchk sik zkssesi". Finally, in year 7, double consonants are removed yielding the final result.
4)
    
7
"  concoction   convalescence   cyclical   cello   "
Returns: "  konkoktion   konvalesense   siklikal   selo   "
Beware of extra spaces.
5)
    
7
""
Returns: ""
Don't forget the empty case.
6)
    
7
"cck xzz aaaaa"
Returns: "k z aaaaa"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ShuffleMethod

Graph Theory



Used in:

TCO '03 Round 3

Used as:

Division I Level Three

Writer:

brett1479

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1871

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4704&pm=1871

Problem Statement

    You will be given a int[] twoShuffle with k elements denoting a method for shuffling a deck of cards. The deck in question will have k cards numbered 1 through k inclusive. Initially, all of the cards in the deck are arranged in ascending order. The ith (1-based) element of twoShuffle describes which card is in position i (1-based) after 2 identical shuffling procedures have completed. You will return a int[] that is exactly like the input, except it describes what a single shuffle would do. A shuffling procedure describes how the relative positions of the cards will change due to the shuffle. More precisely, if element s of a shuffling procedure is p, then the card that was in position p ends up in position s (again, all 1-based). For example,
	twoShuffle = {3,4,1,2}
means that after two shuffles
	the deck   1,2,3,4   would become  3,4,1,2.
You would return {2,3,4,1} since:
	the deck 1,2,3,4  -    after one shuffle  - 2,3,4,1 
		          - after another shuffle - 3,4,1,2.
If there are no possible solutions, return an empty int[]. If there is more than 1 possible solution, return the one that comes first lexicographically. A shuffle X comes lexicographically before a shuffle Y if there is a position j such that, X[i]=Y[i] for all i<j, and X[j]<Y[j].
 

Definition

    
Class:ShuffleMethod
Method:oneTime
Parameters:int[]
Returns:int[]
Method signature:int[] oneTime(int[] twoShuffle)
(be sure your method is public)
    
 

Constraints

-twoShuffle will contain between 3 and 50 elements inclusive.
-Each element of twoShuffle will be between 1 and k inclusive, where k is the number of elements in twoShuffle.
-twoShuffle will contain no duplicate elements.
 

Examples

0)
    
{3,4,1,2}
Returns: { 2,  3,  4,  1 }
The example from above.
1)
    
{1,2,3,4}
Returns: { 1,  2,  3,  4 }
The cards are unshuffled. Since 1,2,3,4 is a valid solution, and is lexicographically first, it is the return value. 2,1,4,3 is another valid solution, but it does not come before 1,2,3,4 lexicographically.
2)
    
{5,1,2,3,4}
Returns: { 3,  4,  5,  1,  2 }
Using the shuffle 3,4,5,1,2 twice we see that
1 -> 3 -> 5
2 -> 4 -> 1
3 -> 5 -> 2
4 -> 1 -> 3
5 -> 2 -> 4
In other words, the deck is transformed as follows:

1,2,3,4,5 -> 3,4,5,2,3 -> 5,1,2,3,4
3)
    
{2,4,6,5,1,8,10,9,3,12,11,13,7,15,16,17,14}
Returns: { 3,  6,  2,  8,  9,  4,  14,  5,  1,  15,  11,  16,  17,  10,  12,  13,  7 }
4)
    
{2,4,6,5,1,8,10,9,3,12,11,13,7}
Returns: { }
5)
    
{10,9,12,8,13,3,4,1,5,11,6,2,7}
Returns: { 9,  1,  4,  12,  11,  7,  3,  2,  10,  5,  13,  8,  6 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CityLink

Graph Theory



Used in:

SRM 170

Used as:

Division I Level Two

Writer:

antimatter

Testers:

lbackstrom , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1864

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4655&pm=1864

Problem Statement

    

There are various cities at points around the x-y plane that are separated by great geographical distances, and thus are hard to travel between. The mayors of the cities have decided that they will undertake a road-paving plan to connect all of the cities. However, they do not know how long this will take.

At time zero, the roads are of zero length. Each time unit, the roads leading out of each city in the four cardinal directions (north, east, south, and west) will be extended by one unit. When roads from two different cities both contain at least one point in common, their two cities are connected, and all cities connected to those two cities are also considered connected. Your job is to figure out how long the construction job will take.

You will be given a int[] x and a int[] y, where the location of the i-th city is at (x[i], y[i]). Given the locations of all the cities in the x-y plane, your method should return the first time unit at which all the cities are connected to each other.

 

Definition

    
Class:CityLink
Method:timeTaken
Parameters:int[], int[]
Returns:int
Method signature:int timeTaken(int[] x, int[] y)
(be sure your method is public)
    
 

Notes

-Connectedness is transitive; i.e., if city A is connected to city B, and B is connected to C, then A is connected to C.
 

Constraints

-x will contain between 1 and 50 elements, inclusive.
-y will contain the same number of elements as x.
-Each element of x will be between -1000000 and 1000000, inclusive.
-Each element of y will be between -1000000 and 1000000, inclusive.
-No two cities will be at the same coordinates.
 

Examples

0)
    
{0,5}
{0,5}	
Returns: 5
The road north from (0,0) will intersect the road west from (5,5) at t = 5.
1)
    
{0,0}
{30,-59}
Returns: 45
2)
    
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,
 27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49}	
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,
 27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49}
Returns: 1
3)
    
{100000}
{-1000000}
Returns: 0
4)
    
{1593,-88517,14301,3200,6,-15099,3200,5881,-2593,11,57361,-92990}
{99531,-17742,-36499,1582,46,34001,-19234,1883,36001,0,233,485}
Returns: 73418

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ShortPalindromes

Dynamic Programming, Recursion



Used in:

SRM 165

Used as:

Division II Level Three

Writer:

vorthys

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1861

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4630&pm=1861

Problem Statement

    

A palindrome is a String that is spelled the same forward and backwards. Given a String base that may or may not be a palindrome, we can always force base to be a palindrome by adding letters to it. For example, given the word "RACE", we could add the letters "CAR" to its back to get "RACECAR" (quotes for clarity only). However, we are not restricted to adding letters at the back. For example, we could also add the letters "ECA" to the front to get "ECARACE". In fact, we can add letters anywhere in the word, so we could also get "ERCACRE" by adding an 'E' at the beginning, a 'C' after the 'R', and another 'R' before the final 'E'. Your task is to make base into a palindrome by adding as few letters as possible and return the resulting String. When there is more than one palindrome of minimal length that can be made, return the lexicographically earliest (that is, the one that occurs first in alphabetical order).

 

Definition

    
Class:ShortPalindromes
Method:shortest
Parameters:String
Returns:String
Method signature:String shortest(String base)
(be sure your method is public)
    
 

Constraints

-base contains between 1 and 25 characters, inclusive.
-Every character in base is an uppercase letter ('A'-'Z').
 

Examples

0)
    
"RACE"
Returns: "ECARACE"
To make "RACE" into a palindrome, we must add at least three letters. However, there are eight ways to do this by adding exactly three letters:
    "ECARACE"  "ECRARCE"  "ERACARE"  "ERCACRE"
    "RACECAR"  "RAECEAR"  "REACAER"  "RECACER"
Of these alternatives, "ECARACE" is the lexicographically earliest.
1)
    
"TOPCODER"
Returns: "REDTOCPCOTDER"
2)
    
"Q"
Returns: "Q"
3)
    
"MADAMIMADAM"
Returns: "MADAMIMADAM"
4)
    
"ALRCAGOEUAOEURGCOEUOOIGFA"
Returns: "AFLRCAGIOEOUAEOCEGRURGECOEAUOEOIGACRLFA"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PartySeats

Simple Search, Iteration, Simulation



Used in:

SRM 164

Used as:

Division II Level Two

Writer:

dgoodman

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1854

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4625&pm=1854

Problem Statement

    It is time to arrange the seating around a circular table for a party. We want to alternate boys and girls around the table. We have a list of all the attendees and their genders. Each attendee is specified by a String that consists of the name, followed by one space, followed by either "boy" or "girl".

In addition to the attendees, we need to seat the HOST (a boy) and the HOSTESS (a girl) with the HOSTESS directly across from the HOST. That means that half the attendees should be on the HOST's left, and half on his right.

Create a class PartySeats that contains a method seating that is given a String[] attendees that lists all the attendees and their genders. The method returns a String[] that gives the seating plan, starting with "HOST" and proceeding clockwise around the table, including all the attendees and the HOSTESS.

If there is more than one possible seating plan, return the one that comes first lexicographically. "First lexicographically" means that each successive element in the return should be chosen to be the earliest alphabetically that is consistent with a legal seating plan. If there is no legal seating plan, the return should contain 0 elements.

 

Definition

    
Class:PartySeats
Method:seating
Parameters:String[]
Returns:String[]
Method signature:String[] seating(String[] attendees)
(be sure your method is public)
    
 

Constraints

-attendees will contain between 1 and 50 elements inclusive
-each element of attendees will consists of a name followed by a single space followed by either "boy" or "girl". There will be no leading or trailing spaces.
-each name will contain between 1 and 20 characters inclusive
-each name will contain only uppercase letters 'A'-'Z'
-no name will be "HOST" or "HOSTESS"
 

Examples

0)
    
{"BOB boy","SAM girl","DAVE boy","JO girl"}
Returns: { "HOST",  "JO",  "BOB",  "HOSTESS",  "DAVE",  "SAM" }
A girl must follow the HOST, and JO comes earliest lexicographically. Then comes a boy, and BOB is the earliest lexicographically. HOSTESS must come next so she can be opposite the HOST and then DAVE and SAM must follow in that order to honor the alternating gender requirement.
1)
    
{"JOHN boy"}
Returns: { }
There are more boys than girls so we cannot alternate.
2)
    
{"JOHN boy","CARLA girl"}
Returns: { }
There is no way to alternate gender and also have the HOST sit directly across from the HOSTESS
3)
    
{"BOB boy","SUZIE girl","DAVE boy","JO girl",
"AL boy","BOB boy","CARLA girl","DEBBIE girl"}
Returns: 
{ "HOST",
 "CARLA",
 "AL",
 "DEBBIE",
 "BOB",
 "HOSTESS",
 "BOB",
 "JO",
 "DAVE",
 "SUZIE" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SMBus

Simple Math, Simulation



Used in:

SRM 162

Used as:

Division II Level Three

Writer:

schveiguy

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1841

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4615&pm=1841

Problem Statement

    

On most modern PC systems, there is a 2-wire bus called the System Management Bus, or SMBus, which is based on the I2C protocol. This bus is used to talk to multiple devices on the system such as temperature sensors, or batteries. The most significant achievement of the I2C protocol is that it requires no more than 2 wires, and is not susceptible to collisions (unlike other hardware protocols, like ethernet). Collisions occur when two masters (devices which transmit messages) try to transmit at the same time and the resulting data is invalid. For I2C, the first bit transmitted by one master which is different than the bit transmitted by another master causes an "arbitration" to occur. The data being transmitted on the bus is the logic and-ed value of all the data being transmitted by the masters. Therefore, if one master is transmitting a '1' and another is transmitting a '0', the '0' will be transmitted and the '1' will not. The master transmitting the '1' detects that it is not able to transmit, and stops transmitting. The arbitration is not detected by the master transmitting the '0', or by the slave receiving the '0', so the message can continue without any collisions.

Since '0' bits that occur earlier in messages always win, the master transmitting the lowest byte always wins arbitration. For example, if one master was transmitting "01234", and another master was transmitting "01245", both masters would transmit the first three bytes, but the first master would win arbitration on the fourth data byte, since '3' is less than '4'.

Multiple masters can start transmissions at the same time, but if a transmission has already started, another master cannot start one in the middle of the transmission. Therefore, if one master is transmitting "01234", and has already transmitted the '0', another master wanting to transmit "1234" cannot start its transmission until the first master is finished.

The speed of transmission of each master is also allowed to vary. The speed at which each byte is transferred is determined by the slowest transmitting master. If a master loses arbitration of the bus, it continues to drive the clock signal (which determines the speed) for the remainder of the current byte, but then stops driving the clock for the rest of the transmission. In other words, the speed that each byte is transmitted at is determined by the slowest master attempting to transmit during that byte, even if the master loses arbitration during that byte.

Given the description of the I2C protocol above, you are to simulate multiple masters transmitting messages on the bus, and return how long it takes to transmit them. You will be given a String[] messages, where each element is a message to be transmitted by a master device, and the messages consist of numeric digits '0'-'9'. You will also be given a int[] times, where each element is the number of milliseconds it takes for the corresponding master to transmit a byte. The master transmitting element i of messages is described by element i of times. Each master that loses arbitration will retry transmitting its message after the current message is finished. Note that all masters try transmitting their messages at the very beginning of the simulation.

 

Definition

    
Class:SMBus
Method:transmitTime
Parameters:String[], int[]
Returns:int
Method signature:int transmitTime(String[] messages, int[] times)
(be sure your method is public)
    
 

Constraints

-messages will contain between 1 and 50 elements, inclusive.
-Each element of messages will contain between 1 and 50 characters, inclusive.
-Each element of messages will consist only of numeric digits '0'-'9', inclusive.
-No element of messages will be a prefix of, or be exactly the same as, any other element of messages.
-times will contain the same number of elements as messages.
-Each element of times will be between 1 and 100, inclusive.
 

Examples

0)
    
{"123","124","134"}
{1,2,3}
Returns: 25

Here is a graph of the bytes that are transmitted, which masters are transmitting for each byte, and how long each byte takes to transmit. '-' means the master is transmitting, and '+' means the master was driving clock, but lost arbitration:

Data:       123124134
Master1:    ---
Master2:    --+---
Master3:    -+ -+ ---
Time taken: 332332333

For the first message, all masters successfully transmit the first byte. Since the slowest is 3 milliseconds, the first byte takes 3 milliseconds to transfer. On the second byte, the third master is arbitrated out since the other two transmit a lower byte. However, the third master still drives the clock for the byte, so it is transmitted at 3 milliseconds. The third byte is transmitted by the first two masters, and even though the second master loses arbitration, it drives the clock at 2 milliseconds. The total time for the first message is therefore 3+3+2 = 8 milliseconds long.

At this point, the second and third master still haven't transmitted their messages. The second message again takes 8 milliseconds because the third master is arbitrated out on the second byte.

The final message is transmitted only by the third master, and therefore takes 9 milliseconds to transmit. The total time for the entire sequence is 8+8+9=25 milliseconds.

1)
    
{"012", "1234", "1233", "1223", "1123"}
{4,1,5,2,9}
Returns: 94

Again, here is a graph which displays the bytes transmitted, which masters are transmitting, and the resulting times for each byte. '-' means the master is transmitting and '+' means the master is driving clock, but lost arbitration:

Data:       0121123122312331234
Master1:    ---
Master2:    +  -+  --+ ---+----
Master3:    +  -+  --+ ----
Master4:    +  -+  ----
Master5:    +  ----
Time taken: 9449999555255551111
2)
    
{"0002019289019101039663222896280025447",
 "00201873554718989597528841094293294387326",
 "010699029378761", "0110118", "011143279122561420",
 "001046384966198", "00200570375817801109530240012",
 "0003163277589822", "01100240744590150136673219652442108",
 "012033596872642679096489479354", "0121059494098",
 "00001002303019117948961792176", "00216399923558", "02014",
 "00224999120803846121427603894967637446889670369",
 "01101009414735635151893037596051740080475886",
 "0000101211809647472761605153430927981533514",
 "176845042961739039392207791589",
 "02000047506929386333221966659552927385017901842706",
 "021001117450487502127241076595509511",
 "021010776262723557108100899515",
 "0210114830738951774606917781619656",
 "0211798433083855430", "00000005842153604632996228135814",
 "0001000766929248550736138555144997170272757787",
 "0001010247593342056062432721557",
 "01100004828618452515832113396660046634951",
 "0132559984733529872911444204991646138116334788",
 "0224149857349431864906523152249992",
 "00001142929552573133212195441932219",
 "0011090498947092002457447355036811372647896489218",
 "000001275414757476198997466", "00010014",
 "00111025861963467834393486017602553072649743",
 "000102085", "00120882661783539",
 "01100018938145727291185020",
 "01100191373790478446634214244459341793", "0001129060",
 "001111287431066271555393813846448",
 "011010160778408696098486370196313", "0002125146381515395"}
{42, 86, 47, 86, 32, 95, 2, 98, 17, 58, 31, 32, 85, 77,
 87, 61, 1, 20, 15, 80, 20, 95, 55, 87, 52, 14, 55, 68,
 2, 66, 67, 3, 28, 97, 100, 67, 65, 20, 28, 77, 93, 64}
Returns: 71048

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Amoebae

String Manipulation, String Parsing



Used in:

SRM 172

Used as:

Division I Level Three

Writer:

Eeyore

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1814

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4665&pm=1814

Problem Statement

    

Your boss, the absent-minded biologist, has gone too far. It's one thing if he chills his lemonade in the lab refrigerator, but this morning he inadvertently rearranged the petri dishes. Now the old bird is calling for Culture X. You've found a dish of amoebae that looks like it might be Culture X, and you even have a photograph of Culture X taken yesterday, but these critters move around freely. They spin and glide through the dish and even flip over, making it hard to tell whether you're still looking at the same culture.

You are given a String[] describing a known state of Culture X. Consider it as a rectangular grid of squares, each of which is marked either '.' or 'X'. An amoeba is a component formed of directly adjacent 'X' squares. If an amoeba is composed of more than one 'X' square, then each of its 'X' squares shares an edge with at least one other 'X' square in the same amoeba. No two 'X' squares belonging to different amoebae may share an edge, but they are permitted to neighbor each other diagonally. An amoeba may contain holes. For example, the dish below contains five amoebae. Observe that one of them comprises exactly two squares, while another consists of a single square.


          ...XXXXXXX.......
          ....X.X.X........
          ...XXXXXX........
          ...............XX
          ......X.....XX..X
          .XXXXX........X.X
          .X.XXX.......XXXX

Given a second String[] with the same dimensions, decide whether it depicts the same collection of amoebae. Amoebae are considered identical under rotation (at right angles), reflection (in the horizontal or vertical axis), and translation (to any extent, as long as the amoeba remains wholly within the petri dish). Return 0 if both dishes contain the same amoebae. Otherwise, return the sum of these two figures: (a) the number of amoebae in Culture X that are not present in the candidate dish and (b) the number of amoebae in the candidate dish that are not present in Culture X.

 

Definition

    
Class:Amoebae
Method:cultureX
Parameters:String[], String[]
Returns:int
Method signature:int cultureX(String[] known, String[] candidate)
(be sure your method is public)
    
 

Constraints

-known and candidate have the same number of elements
-known and candidate each have between 1 and 50 elements, inclusive
-all elements of known and candidate are equally long
-elements of known and candidate are each between 1 and 50 characters long, inclusive
-all characters in known and candidate must be either '.' or 'X'
 

Examples

0)
    
{"...XXXXXXX.......",
 "....X.X.X........",
 "...XXXXXX........",
 "...............XX",
 "......X.....XX..X",
 ".XXXXX........X.X",
 ".X.XXX.......XXXX"}
{"X.X..........XXXX",
 "XXX...XX......X.X",
 "X.X...XX........X",
 "XXX...XX.......XX",
 "X.X....X.X.......",
 "XXX...XX.X.......",
 "X.......X........"}
Returns: 0
You've found Culture X! All the amoebae have been translated since yesterday. The one that was in the lower right corner has also been reflected in the horizontal axis. The one at lower left has been reflected and rotated, as has the big ugly one with two holes. The amoeba formed of two squares has been rotated.
1)
    
{"...XXXXXXX.......",
 "....X.X.X........",
 "...XXXXXX........",
 "...............XX",
 "......X.....XX..X",
 ".XXXXX........X.X",
 ".X.XXX.......XXXX"}
{"X.X..........XXXX",
 "XXX...XX......X.X",
 "X.X...XX........X",
 "......XX.......XX",
 "X.X....X.X.......",
 "XXX...XX.X.......",
 "X.......X........"}
Returns: 3
Four amoebae from Culture X are present in the candidate petri dish, but the big ugly one with two holes is missing. Furthermore, the candidate dish has two amoebae that were not present in Culture X. In total, this makes a difference of 1+2=3.
2)
    
{"......................",
 "....XXX...............",
 "..X...X......XX.XX....",
 "..XX.........XX.XX....",
 "...XX.................",
 "..........X...X..XXXX.",
 "..XXX.....XX.XX.XX..XX",
 "..X........X.X..X....X",
 ".....XX....XXX..X....X",
 ".....XX.....X...XX..XX",
 "............X....XXXX."}
{"....X......XX.XX.XX...",
 "....XXX....XX.XX.XX...",
 ".........XX...........",
 ".........XX...........",
 "......................",
 "..X....XXXX....X......",
 "..X...XX..XX...X......",
 ".XXX..X....X..XXX.....",
 ".X.X..X....X..X.X.....",
 "XX.XX.XX..XX.XX.XX....",
 "X...X..XXXX..X...X...."}
Returns: 4
Compared to Culture X, the candidate dish has an extra Y-shaped amoeba and an extra two-by-two amoeba, but it's missing a small L-shaped amoeba, and it doesn't have the squiggly one at all. That makes a symmetric difference of 4.
3)
    
{".XXXX.X...X...XXXX..", 
"X..XXXXXXX.X.....XX.", 
".X.X.XX....X..XXX..X", 
"..XXX.X.X....X......", 
".XXXXX...X.....XXXX.", 
"..X.XXX..XX....XXX.X", 
".......XXX..X.X...XX", 
"XX....X.....X...X.X.", 
".....X.....XX..XXX.X", 
"X...XX.X.X..X....X.X", 
".X........X.........", 
".X..X.........X.....", 
"..X.X..X..........XX", 
"........X.X...X.XX..", 
"....X.......X.X..X.X", 
"....XX..X..X.X.X...X", 
"X.....X.........X.X.", 
"X.X...X.............", 
"..XXX.X...X..X..XX..", 
"X.......XX...X......"}
{".X.....X.X......XX.X", 
"X.X.X..X..XX........", 
"X..XXX......X....XX.", 
"XXXXX.............X.", 
"XX.XXX...X.XX.XX..X.", 
".XX.XX..XX.....X....", 
"XXXX.X.X........XXX.", 
".X....X..X..X.......", 
".X.X..X......X.X...X", 
".X..XXX..X.........X", 
"X....X....X..X....X.", 
".XX.....X......X....", 
"......XXXX....X.....", 
"...X...........X..XX", 
"X.X...X....X.XX.....", 
"X.X.XX..X......X....", 
"X.X.XX.XX....X..X.X.", 
"XX..XX..XX...XX...X.", 
".X..X.XX....X...X...", 
"..X..XX.XX..X.XX...."}
Returns: 0
4)
    
{".....XXX...X.....XX.....XX.XX..XX..", 
"..X.XX.XX.X....XXX....X......X.....", 
".....XX...X....X.X....X.X.X........", 
"X.....X.......XXX.X....X..XX.X.....", 
".X.X....X.X........X..........XX...", 
"........XX........X.....X..X.X.....", 
".X..X...X...XX.X..X.....X..........", 
"..............X......X...X....X..X.", 
"XX..X.....XX..X...X...X.X..X....X..", 
".X....XX..X...............X.X.XXXX.", 
"...XXXXX.....X...X....X.XX..XXX..X.", 
".........X..XX....X.X......XXXX....", 
"..XXXX.X..XXX.X...........X..X.XX..", 
"X...X...........X..X.X..X.XX..X.X..", 
"..X....X.....X..X.X....X..X.X..XXXX", 
"X..XXX..X..XX.XX.X..X...X...X..X.XX", 
"....X....X.X...X..X..X..XXX...XXXX.", 
".X..XX.XX.....X..XX..............XX", 
"X..........X..X......XXXX.....X..X.", 
".X.XXX...X..X..XX.X.X.X.X..X.......", 
"X....X.........X....XXXX..X....X..X", 
"..X.XX...X......X.X.......XX....X..", 
"X.XXXX....X.XXX..XX..XXXX.X.XX.....", 
"XXX.X........X.X..X..X....X..X.....", 
"......X..X..XX..X.....XX........X..", 
"...X.....XX..X..X..X.X......XX..X.X", 
"..X..X.......XX......X......X...XX.", 
"..X.XX......XX.X..X.....X...X.X..X.", 
".X.X.XX.XXX.X..X.X.................", 
".......X.XX..X..X..X.....X.X..XX..X", 
"X...XX.......X...X...X.X....X......", 
"X.......X.X......X.X.X......X.....X", 
"....X.X.X.X....XXX..XX.....XX.X..X.", 
"...X..X.X.XX......X.....XX.XXXX....", 
"..X......X...X.X...X...X.X.XXXX...X"}
{"..XX......X..XX.X....X..X.XX..X....", 
"...X.X.X.......X..X....X...........", 
".XXX.X.XXX.....X.X.X..XX.XX.X.XX.XX", 
"X...X......X.X........X...X.X.....X", 
"X.....X....X...XX....X.X........XX.", 
"..XXX...XXX............X.XX..XX..XX", 
"....X.X..X..X.X...X.X....X.XX...X..", 
".XX..X........XX..X......XX..X....X", 
"...X......X...X..X...XX...XXX..X.X.", 
"..XX...X..X...X...X.XX.....X.....X.", 
".XX.X........X..X..X......XX.X.XX..", 
".X.X..XX..X.XX......X....X.........", 
"X..X.X..X........X.....X..X..XX...X", 
"X.X.........X.XXX..XX..X.........X.", 
".........X......XX.....X.....X..X.X", 
"X..X.X.XXX.X.....X...X...X...X..X.X", 
"X......X..X.XX.X......X....XX.....X", 
"X.X...................X...X..X..XX.", 
".........X........X..XX..X......X.X", 
".X....X.X.X.......X..XX..XX.XXX...X", 
".................XXX...XX...X..X...", 
"..X...X...XX.....X.....X..XX....XX.", 
".......XXX.XX....X...XX..XXX.X....X", 
"........X...XXXX..X..........X.....", 
"..........XX.X.XX.X.........XX....X", 
"...X.....X.X.................X....X", 
"...XX.X.....X.....XXXX...X...X.X...", 
".............X.....X..X..X.X.X..X..", 
"...............X....X....X..X.X.X.X", 
".XX..XX........X.....X.XX....X....X", 
"...X....X..X...XXX..X........X.....", 
"X.XXX.XX..X......XX.X......X.X.X...", 
".XX.X....X..X..X.X.................", 
"....XXX.X.X......XX.....XX...X.XX..", 
"......X....XX..X.....X...XX.X.....X"}
Returns: 64

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PermutationValues

Advanced Math, Recursion, Search



Used in:

SRM 161

Used as:

Division I Level Three

Writer:

brett1479

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1808

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4610&pm=1808

Problem Statement

    You will be given two int[]s lows and highs describing a group of integer ranges. lows[i] and highs[i] represent the lower and upper inclusive bounds for the ith range of numbers. None of the ranges will overlap. The total group of numbers used in this problem will be the combination of the ranges given in lows and highs.



You will also be given a numeric String lexPos and a String[] retInts containing numeric Strings. Assume you listed all possible permutations of the given group of numbers in ascending lexicographical order (no repeated permutations). Find the permutation A that is in position lexPos lexicographically. Return a int[] with the same number of elements as retInts whose kth element is A[retInts[k]]. lexPos is a 0-based index into the list of possible permutations. Each element of retInts is a 0-based index into the relevant permutation.



In a lexicographical ordering, permutations are ordered by their first elements, with ties broken by their second elements, further ties broken by their third elements, and so forth. If lexPos is greater than the total possible number of lexicographical orderings (without repeats) T, then use lexPos%T instead of lexPos (% denotes mod).
 

Definition

    
Class:PermutationValues
Method:getValues
Parameters:int[], int[], String, String[]
Returns:int[]
Method signature:int[] getValues(int[] lows, int[] highs, String lexPos, String[] retInts)
(be sure your method is public)
    
 

Notes

-Each element of retInts and lexPos will fit in a long.
 

Constraints

-lows will contain between 1 and 50 elements inclusive
-highs will contain the same number of elements as lows
-lexPos will be between 0 and (2^63)-1 inclusive
-lexPos will contain only digits (0-9), will not have extra leading zeros, and will not contain whitespace
-lexPos will contain between 1 and 50 characters inclusive
-retInts will contain between 1 and 50 elements inclusive
-Each element of lows will be between -2^31 and (2^31)-1 inclusive
-Each element of highs will be between -2^31 and (2^31)-1 inclusive
-Element k of lows will not be greater than element k of highs
-No two ranges will overlap
-Each element of retInts will contain only digits (0-9), will not have extra leading zeros, and will not contain whitespace
-Each element of retInts will contain between 1 and 50 characters inclusive
-Each element of retInts will be between 0 and tot-1 inclusive, where tot is the total amount of numbers in all ranges combined
 

Examples

0)
    
{1}
{4}
"0"
{"0","1","2","3"}
Returns: { 1,  2,  3,  4 }
The 0th permutation lexicographically is the sequence 1,2,3,4.
1)
    
{1}
{3}
"5"
{"0","1","2"}
Returns: { 3,  2,  1 }
The 6 possible permutations, in order, are :

0) 1, 2, 3

1) 1, 3, 2

2) 2, 1, 3

3) 2, 3, 1

4) 3, 1, 2

5) 3, 2, 1

lexPos is 5 so you return the 0th, 1st, and 2nd elements of permutation 5
2)
    
{1,16}
{5,20}
"1000000"
{"0","1","2","3","4","5","6","7","8","9","1","2","3"}
Returns: { 3,  18,  19,  4,  20,  2,  16,  17,  1,  5,  18,  19,  4 }
Notice the repeated elements in retInts
3)
    
{1}
{5}
"100000000000001"
{"0","1","2","3","4"}
Returns: { 2,  4,  5,  3,  1 }
lexPos is very big.
4)
    
{-1000000000,500000}
{0,2000000000}
"99999999999999999"
{"2999500000","1234123","123344","9293939","2999500001","2999499950"}
Returns: { 1999999987,  -998765877,  -999876656,  -990706061,  1999999982,  1999999949 }
5)
    
{9}
{9}
"999999"
{"0"}
Returns: { 9 }
6)
    
{0,-100,101}
{99,-11,100000000}
"100000000000009"
{"4","100000087","7"}
Returns: { -96,  99999993,  -93 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DotNotation

String Parsing



Used in:

SRM 152

Used as:

Division I Level Three

Writer:

leadhyena_inran

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1762

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4565&pm=1762

Problem Statement

    

In Chapter 7 of W.V. Quine's book "Mathematical Logic", Quine speaks about the necessity of parentheses but also of their obsfucating nature. To combat this he introduces "a graphical notation of dots". Where parentheses determine the outside boundaries of operands by marking them directly, dot notation does this by placing dots on each side of the operator. The left operand of the operator is determined by the number of dots prefixed to the operator; the operand is the substring with its end at the beginning of the prefixed dots and with its beginning at the end of the next larger grouping of dots suffixed to another operator, or at the beginning of the expression whichever comes first. The right side of the operator is determined likewise; it is the substring starting at the end of the suffixed dots and has its end at the beginning of the next larger grouping of dots prefixed to another operator or at the end of the expression, whichever comes first.

To be specific, all dot notation will be a <DotNotation> of this form (quotes added for clarity):

<DotNotation> := <Number> | <DotNotation><Dots><Operator><Dots><Number>

<Dots> := "" | <Dots>"."

<Operator> := "+" | "-" | "*" | "/"

<Number> := exactly one of "0123456789"

If an operator's operands reach across the entire expression, the operator is said to be dominant. Evaluation in dot notation involves finding the dominant operator, evaluating the left and right operands of that operator, and then evaluating that operator last. For example: in the dot notation expression "2*.1+3", "2" is the left operand of the '*' (consider no dots as a grouping of 0 dots) and "1+3" is the right operand of the '*', so this can be read with parentheses as "2*(1+3)", the '*' is dominant, and the expression evaluates to 8. Likewise, "2*.1..+3" refers to the expression "(2*1)+3", the '+' is dominant, and the expression evaluates to 5.



Dot notation can be ambiguous if there is more than one dominating operator. For example, in the expression "3+.5.*7" either operator may be dominant (both operators reach across the entire expression unopposed) so this could be parenthesized as either "3+(5*7)" or "(3+5)*7" and the expression could evaluate to either 38 or 56 respectively. There are even expressions that have no dominating operator, such as "1+...2....*.8..+7". Since there is no way to parenthesize this expression consistent with its dot notation, it cannot be legally evaluated.

You will be given a String in dot form, and you'll need to return the number of unique integers that the expression can evaluate to. For this problem, a specific evaluation is illegal if any part of the evaluation involves division by 0, any operand evaluates to a value that is less than -2000000000 or greater than 2000000000, or if the expression has no dominating operator thus preventing evaluation. If all possible evaluations of the dot notation are illegal return 0.

 

Definition

    
Class:DotNotation
Method:countAmbiguity
Parameters:String
Returns:int
Method signature:int countAmbiguity(String dotForm)
(be sure your method is public)
    
 

Notes

-There is no normal order of operations in this problem; thus a+b*c is ambiguous.
 

Constraints

-dotForm will be between 1 and 25 characters long, inclusive.
-dotForm will be a <DotNotation> as described above.
 

Examples

0)
    
"2"
Returns: 1
A single digit by itself has only one interpretation.
1)
    
"9+5*3"
Returns: 2
This could be read (9+5)*3 or as 9+(5*3). Keep in mind that no order of operations is to be assumed.
2)
    
"9+5.*3"
Returns: 1
Here, the dot prefixed to the * gives it dominance, and this can only be read as (9+5)*3.
3)
    
"1+2.*.3+4"
Returns: 1
The * is dominant here, so this is read as (1+2)*(3+4), and 21 is the only number it can be evaluated to.
4)
    
"9*8+7*6-5+4*3/2./9"
Returns: 99
5)
    
"1+...2....*.8..+7"
Returns: 0
Notice here how none of the operators in the expression can be dominating. Since none of these operators are dominating, none of these operators may be evaluated last, meaning that there is no valid interpretation of this expression.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PowerOutage

Graph Theory



Used in:

SRM 144

Used as:

Division II Level Three

Writer:

leadhyena_inran

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1697

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4515&pm=1697

Problem Statement

    

You work for an electric company, and the power goes out in a rather large apartment complex with a lot of irate tenants. You isolate the problem to a network of sewers underneath the complex with a step-up transformer at every junction in the maze of ducts. Before the power can be restored, every transformer must be checked for proper operation and fixed if necessary. To make things worse, the sewer ducts are arranged as a tree with the root of the tree at the entrance to the network of sewers. This means that in order to get from one transformer to the next, there will be a lot of backtracking through the long and claustrophobic ducts because there are no shortcuts between junctions. Furthermore, it's a Sunday; you only have one available technician on duty to search the sewer network for the bad transformers. Your supervisor wants to know how quickly you can get the power back on; he's so impatient that he wants the power back on the moment the technician okays the last transformer, without even waiting for the technician to exit the sewers first.

You will be given three int[]'s: fromJunction, toJunction, and ductLength that represents each sewer duct. Duct i starts at junction (fromJunction[i]) and leads to junction (toJunction[i]). ductlength[i] represents the amount of minutes it takes for the technician to traverse the duct connecting fromJunction[i] and toJunction[i]. Consider the amount of time it takes for your technician to check/repair the transformer to be instantaneous. Your technician will start at junction 0 which is the root of the sewer system. Your goal is to calculate the minimum number of minutes it will take for your technician to check all of the transformers. You will return an int that represents this minimum number of minutes.

 

Definition

    
Class:PowerOutage
Method:estimateTimeOut
Parameters:int[], int[], int[]
Returns:int
Method signature:int estimateTimeOut(int[] fromJunction, int[] toJunction, int[] ductLength)
(be sure your method is public)
    
 

Constraints

-fromJunction will contain between 1 and 50 elements, inclusive.
-toJunction will contain between 1 and 50 elements, inclusive.
-ductLength will contain between 1 and 50 elements, inclusive.
-toJunction, fromJunction, and ductLength must all contain the same number of elements.
-Every element of fromJunction will be between 0 and 49 inclusive.
-Every element of toJunction will be between 1 and 49 inclusive.
-fromJunction[i] will be less than toJunction[i] for all valid values of i.
-Every (fromJunction[i],toJunction[i]) pair will be unique for all valid values of i.
-Every element of ductlength will be between 1 and 2000000 inclusive.
-The graph represented by the set of edges (fromJunction[i],toJunction[i]) will never contain a loop, and all junctions can be reached from junction 0.
 

Examples

0)
    
{0}
{1}
{10}
Returns: 10
The simplest sewer system possible. Your technician would first check transformer 0, travel to junction 1 and check transformer 1, completing his check. This will take 10 minutes.
1)
    
{0,1,0}
{1,2,3}
{10,10,10}
Returns: 40
Starting at junction 0, if the technician travels to junction 3 first, then backtracks to 0 and travels to junction 1 and then junction 2, all four transformers can be checked in 40 minutes, which is the minimum.
2)
    
{0,0,0,1,4}
{1,3,4,2,5}
{10,10,100,10,5}
Returns: 165
Traveling in the order 0-1-2-1-0-3-0-4-5 results in a time of 165 minutes which is the minimum.
3)
    
{0,0,0,1,4,4,6,7,7,7,20}
{1,3,4,2,5,6,7,20,9,10,31}
{10,10,100,10,5,1,1,100,1,1,5}
Returns: 281
Visiting junctions in the order 0-3-0-1-2-1-0-4-5-4-6-7-9-7-10-7-8-11 is optimal, which takes (10+10+10+10+10+10+100+5+5+1+1+1+1+1+1+100+5) or 281 minutes.
4)
    
{0,0,0,0,0}
{1,2,3,4,5}
{100,200,300,400,500}
Returns: 2500

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PointsOnAxis

Brute Force, Recursion



Used in:

SRM 159

Used as:

Division I Level Three

Writer:

dimkadimon

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1670

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4600&pm=1670

Problem Statement

    

There are several distinct points located on the non-negative side of the x-axis. One of those points is at the origin (at 0). For each unique pair of points we write down the distance between them. Note that pairs (a, b) and pairs (b, a) are not unique pairs.

Given a int[] of those distances, return a int[] containing the locations of all points arranged in ascending order. If more than one set of locations is possible then return the set (represented as a int[]) which is lexicographically earliest (see example 1). A int[], n, comes before a int[], m, lexicographically if and only if, for the first element in which they differ, the element of n is smaller. If no set of locations is possible then return an empty int[].

For example: distances = {5, 2, 1, 6, 2, 3, 3, 4, 5, 6, 3, 9, 1, 4, 1}. This in order is {1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 9}. The only possible arrangement of points is the following:

  0    1    2    3    4    5    6    7    8    9
--x----|----|----x----x----x----x----|----|----x--

Here 'x' represents a point. Thus the method should return {0, 3, 4, 5, 6, 9}

 

Definition

    
Class:PointsOnAxis
Method:findPoints
Parameters:int[]
Returns:int[]
Method signature:int[] findPoints(int[] distances)
(be sure your method is public)
    
 

Notes

-There cannot be more than one point at the same location, because elements in distances are never 0.
 

Constraints

-the number of elements in distances will be N(N-1)/2, where N is the number of points.
-N will be between 2 and 10 inclusive.
-each element in distances will be between 1 and 1000000 inclusive.
 

Examples

0)
    
{5, 2, 1, 6, 2, 3, 3, 4, 5, 6, 3, 9, 1, 4, 1}
Returns: { 0,  3,  4,  5,  6,  9 }
See above.
1)
    
{20,100,120}
Returns: { 0,  20,  120 }
The possible sets of locations are {0,100,120} and {0,20,120}. Since 20 comes before 100, the method should return {0,20,120}.
2)
    
{1,2,3,4,5,7}
Returns: { 0,  2,  3,  7 }
3)
    
{1,2,4}
Returns: { }
There are no possible sets of locations.
4)
    
{237601, 843904, 56786, 429289, 52254, 83576, 220417,
606303, 180815, 191688, 185347, 154025, 17184, 787118,
414615, 791650, 760328, 623487, 372503, 4532, 26790,
163631, 377035, 345713, 208872, 31322, 168163, 136841}
Returns: { 0,  52254,  56786,  83576,  220417,  237601,  429289,  843904 }
5)
    
{1, 1, 1, 1, 2, 2, 3, 4, 4, 5, 5, 5, 6, 6, 7}
Returns: { 0,  1,  2,  5,  6,  7 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

CCipher

Encryption/Compression, String Manipulation



Used in:

SRM 147

Used as:

Division II Level One

Writer:

axchma

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1667

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4540&pm=1667

Problem Statement

    

Julius Caesar used a system of cryptography, now known as Caesar Cipher, which shifted each letter 2 places further through the alphabet (e.g. 'A' shifts to 'C', 'R' shifts to 'T', etc.). At the end of the alphabet we wrap around, that is 'Y' shifts to 'A'.

We can, of course, try shifting by any number. Given an encoded text and a number of places to shift, decode it.

For example, "TOPCODER" shifted by 2 places will be encoded as "VQREQFGT". In other words, if given (quotes for clarity) "VQREQFGT" and 2 as input, you will return "TOPCODER". See example 0 below.

 

Definition

    
Class:CCipher
Method:decode
Parameters:String, int
Returns:String
Method signature:String decode(String cipherText, int shift)
(be sure your method is public)
    
 

Constraints

-cipherText has between 0 to 50 characters inclusive
-each character of cipherText is an uppercase letter 'A'-'Z'
-shift is between 0 and 25 inclusive
 

Examples

0)
    
"VQREQFGT"
2
Returns: "TOPCODER"
1)
    
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
10
Returns: "QRSTUVWXYZABCDEFGHIJKLMNOP"
2)
    
"TOPCODER"
0
Returns: "TOPCODER"
3)
    
"ZWBGLZ"
25
Returns: "AXCHMA"
4)
    
"DBNPCBQ"
1
Returns: "CAMOBAP"
5)
    
"LIPPSASVPH"
4
Returns: "HELLOWORLD"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DQuads

Brute Force



Used in:

TCCC '03 Finals

Used as:

Division I Level One

Writer:

lars2520

Testers:

brett1479 , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1663

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4497&pm=1663

Problem Statement

    We have a list of airline flights (directed edges between two nodes in a graph), and want to determine how many distinct directed quadrilaterals (directed cycles of length 4, which contain 4 distinct nodes) there are in the flight graph such that the nodes on opposite corners of the quadrilateral are not connected in either direction. Thus, we would count the graph on the left, but not the one on the right (the diagonal edge can be directed either way, or both ways - it doesn't matter):
      o--->o      o--->o
      ^    ^      ^\   ^
      |    |      | \  |
      |    v      |  \ v
      o<-->o      o<-->o
You will be given a String[] flights representing the flights. Element i of flights is a single space delimited list of integers (without extra leading 0's or leading/trailing spaces), where each integer j in the list indicates that there is an edge from i to j. An integer, j may appear more than once in element i meaning that there are multiple flights from i to j, each of which should be considered distinct. However, regardless of how many flights there are from one node to another, a quadrilateral must contain exactly 4 distinct nodes. Two quadrilaterals are considered distinct if and only if the sets of flights that they use are distinct. Thus, there may be many quadrilaterals that use the same four nodes, but different edges. Your task is to write a class DQuads, with a method count, which returns the total number of distinct quadrilaterals.
 

Definition

    
Class:DQuads
Method:count
Parameters:String[]
Returns:int
Method signature:int count(String[] flights)
(be sure your method is public)
    
 

Constraints

-flights will contain between 4 and 50 elements, inclusive.
-Each element of flights will be a single space delimited list of integers, with no extra leading 0's and no leading or trailing spaces.
-Each integer in each element of flights will be between 0 and the length of flights - 1, inclusive.
-Each element of flights will contain between 0 and 50 characters, inclusive.
-Element i of flights will not contain the integer i as one of its terms.
 

Examples

0)
    
{"1 1 1 1 1 1 1 1 1 1","2","3","0"}
Returns: 10
This is just a single directed square. Since there are 10 edges from 0 to 1, there are 10 distinct, directed quadrilaterals.
1)
    
{"1 1 1 1 1 1 1 1 1 1","2","3","0 1"}
Returns: 0
This is the same as the last example, except with a cross edge from 3 to 1 included. The cross edge is in all the quadrilaterals from the previous example, and so none of them count any more.
2)
    
{"","6 0 2","","6 6 4","6 5 5 0","",""}
Returns: 0
3)
    
{"1", "0 2", "3 1", "0"}
Returns: 1
4)
    
{"3 4 8 3 7","0","4 0","","1 7 7 0","0 0 2","5 4 8 3 8","5 4 5 5 6",""}
Returns: 6
5)
    
{"3 3 6","0","5 5 6 3","2 4 1 4","6 3 6 6","3","5 0 2"}
Returns: 26
6)
    
{"8 1 2 4 8 12 4 5 11 10 6 2","5 3 15 7 15 15 12 0 8 9 2 0 13 9 8 7 4 7 9 11 11",
 "6 7 11 9 10 1 12 9","6 6 9 7 6 1 14 1 6 7 10 6 15 6 14 16 10 11 13 4 7",
 "14 15 16 0 13 2 5 16 6","2 7 16 13 16 10 16 0 8 6 0 2 6",
 "8 8 4 11 3 14 9 14 14 0 5 10 13 3 11 9 5 7","13 15 6 1 3 13 6 6 8 9 6 4 10",
 "4 0 1 4 12 1 2 0 14 9 6 4 16 10 7 6 9 7 13 14","11 12 4 12",
 "6 4 4 9 3 1 8 0 14 14 9 14 16 5 8 16 5 12 4 5 1 12",
 "14 7 14 8 4 16 6 3 13 6 10 7 13 3","15 4","12 14 14 0 8 12 11 4 3 1 12 1",
 "13 4 4 6 12 0","9 0 2 9 5 10","6 15 6 13 4 5 1 6"}
Returns: 140

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PenLift

Geometry, Graph Theory



Used in:

SRM 144

Used as:

Division I Level Three

Writer:

LunaticFringe

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1649

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4515&pm=1649

Problem Statement

    

NOTE: There are images in the examples section of this problem statement that help describe the problem. Please view the problem statement in the HTML window to view them.

Given a picture composed entirely of horizontal and vertical line segments, calculate the minimum number of times you must lift your pen to trace every line segment in the picture exactly n times.

Each line segment will be of the form "<x1> <y1> <x2> <y2>" (quotes for clarity), representing a segment from (x1,y1) to (x2,y2). Segments may cross each other. Segments may also overlap, in which case you should count the overlapping region as appearing in the drawing only once. For example, say the drawing were composed of two lines: one from (6,4) to (9,4), and one from (8,4) to (14,4). Even though they overlap from (8,4) to (9,4), you should treat the drawing as if it were a single line from (6,4) to (14,4). You would not need to lift your pen at all to trace this drawing.

 

Definition

    
Class:PenLift
Method:numTimes
Parameters:String[], int
Returns:int
Method signature:int numTimes(String[] segments, int n)
(be sure your method is public)
    
 

Notes

-The pen starts on the paper at a location of your choice. This initial placement does not count toward the number of times that the pen needs to be lifted.
 

Constraints

-segments will contain between 1 and 50 elements, inclusive.
-Each element of segments will contain between 7 and 50 characters, inclusive.
-Each element of segments will be in the format "<X1>_<Y1>_<X2>_<Y2>" (quotes for clarity). The underscore character represents exactly one space. The string will have no leading or trailing spaces.
-<X1>, <Y1>, <X2>, and <Y2> will each be between -1000000 and 1000000, inclusive, with no unnecessary leading zeroes.
-Each element of segments will represent a horizontal or vertical line segment. No line segment will reduce to a point.
-n will be between 1 and 1000000, inclusive.
 

Examples

0)
    
{"-10 0 10 0","0 -10 0 10"}
1
Returns: 1

This picture looks like a plus sign centered at the origin. One way to trace this image is to start your pen at (-10,0), move right to (10,0), lift your pen and place it at (0,-10), and then move up to (0,10). There is no way to trace the picture without lifting your pen at all, so the method returns 1.

1)
    
{"-10 0 0 0","0 0 10 0","0 -10 0 0","0 0 0 10"}
1
Returns: 1

The picture is the same as the previous example, except that it has been described with four line segments instead of two. Therefore, the method still returns 1.

2)
    
{"-10 0 0 0","0 0 10 0","0 -10 0 0","0 0 0 10"}
4
Returns: 0

You are now required to trace each segment exactly 4 times. You can do so without lifting your pen at all. Start at (0,0). Move your pen left to (-10,0), then back right to (0,0), then left again to (-10,0), then right again to (0,0). You have now traced the first line segment 4 times. Repeat this process for the other three segments as well. Since no pen lifts were required, the method returns 0.

3)
    
{"0 0 1 0",   "2 0 4 0",   "5 0 8 0",   "9 0 13 0",
 "0 1 1 1",   "2 1 4 1",   "5 1 8 1",   "9 1 13 1",
 "0 0 0 1",   "1 0 1 1",   "2 0 2 1",   "3 0 3 1",
 "4 0 4 1",   "5 0 5 1",   "6 0 6 1",   "7 0 7 1",
 "8 0 8 1",   "9 0 9 1",   "10 0 10 1", "11 0 11 1",
 "12 0 12 1", "13 0 13 1"}
1
Returns: 6

The picture looks like this:

To trace the picture using the minimum number of pen lifts, refer to the following diagram:

Start by placing your pen at the yellow dot. Trace the yellow square. Now lift your pen and place it on the red dot. Move downward, tracing the vertical line segment, and then around the perimeter of the red rectangle. Lift your pen again and place it on the green dot. Trace the green lines using the same method as you did for the red lines. Lift your pen a third time, placing it on the magenta dot. Trace the magenta lines in a similar fashion. You will need to lift your pen three more times to trace each of the leftover white segments, for a grand total of 6 pen lifts.

4)
    
{"-2 6 -2 1",  "2 6 2 1",  "6 -2 1 -2",  "6 2 1 2",
 "-2 5 -2 -1", "2 5 2 -1", "5 -2 -1 -2", "5 2 -1 2",
 "-2 1 -2 -5", "2 1 2 -5", "1 -2 -5 -2", "1 2 -5 2",
 "-2 -1 -2 -6","2 -1 2 -6","-1 -2 -6 -2","-1 2 -6 2"}
5
Returns: 3

This is an example of overlap. Once all the segments are drawn, the picture looks like this:

You would need to lift your pen 3 times to trace every segment in this drawing exactly 5 times.

5)
    
{"-252927 -1000000 -252927 549481","628981 580961 -971965 580961",
"159038 -171934 159038 -420875","159038 923907 159038 418077",
"1000000 1000000 -909294 1000000","1000000 -420875 1000000 66849",
"1000000 -171934 628981 -171934","411096 66849 411096 -420875",
"-1000000 -420875 -396104 -420875","1000000 1000000 159038 1000000",
"411096 66849 411096 521448","-971965 580961 -909294 580961",
"159038 66849 159038 -1000000","-971965 1000000 725240 1000000",
"-396104 -420875 -396104 -171934","-909294 521448 628981 521448",
"-909294 1000000 -909294 -1000000","628981 1000000 -909294 1000000",
"628981 418077 -396104 418077","-971965 -420875 159038 -420875",
"1000000 -1000000 -396104 -1000000","-971965 66849 159038 66849",
"-909294 418077 1000000 418077","-909294 418077 411096 418077",
"725240 521448 725240 418077","-252927 -1000000 -1000000 -1000000",
"411096 549481 -1000000 549481","628981 -171934 628981 923907",
"-1000000 66849 -1000000 521448","-396104 66849 -396104 1000000",
"628981 -1000000 628981 521448","-971965 521448 -396104 521448",
"-1000000 418077 1000000 418077","-1000000 521448 -252927 521448",
"725240 -420875 725240 -1000000","-1000000 549481 -1000000 -420875",
"159038 521448 -396104 521448","-1000000 521448 -252927 521448",
"628981 580961 628981 549481","628981 -1000000 628981 521448",
"1000000 66849 1000000 -171934","-396104 66849 159038 66849",
"1000000 66849 -396104 66849","628981 1000000 628981 521448",
"-252927 923907 -252927 580961","1000000 549481 -971965 549481",
"-909294 66849 628981 66849","-252927 418077 628981 418077",
"159038 -171934 -909294 -171934","-252927 549481 159038 549481"}
824759
Returns: 19

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TelephoneGame

Graph Theory



Used in:

TCCC '03 Semifinals 2

Used as:

Division I Level Three

Writer:

brett1479

Testers:

Logan , lbackstrom , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1639

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4492&pm=1639

Problem Statement

    A bunch of people in a large park area are setting up a telephone network using receivers directly connected by wires. There is a lot of spare wire, so the connections need not be straight. The only restriction on the medium is that there be no crossings, since they could cause interference. In other words, if observed from a helicopter above the park, none of the wires can appear to be crossing over one another. Initially, the group of people set up a base network where person 0 is connected to person 1, person 1 is connected to person 2, ..., person i is connected to person i+1, ..., and the last person is connected back to person 0 forming a cycle. Afterwards many other connections were built. The problem is, some of the new connections may have forced crossings to occur.



Given the additional connections that were formed, your method will determine the minimum number of connections that need be removed such that there will not be any crossings. Note that, given a particular set of connections, if it is possible to lay the wires such that they will not cross, the people will do so. This means the people may change their locations and how much wire they use in order to remove crossings. They will not succeed if a crossing is inevitable. Also, since the base network must not be damaged, the removed connections cannot include any of the base network connections.



You will be given 2 int[]s connect1 and connect2 representing the additional connections formed. If the kth elements of connect1 and connect2 are a and b respectively, person a and person b have formed a connection. Note, connections are symmetric, so if a and b are connected then b and a are connected. You will also be given an int numPeople representing the number of people forming the network. Each element of connect1 and connect2 will be integers between 0 and numPeople-1 inclusive.
 

Definition

    
Class:TelephoneGame
Method:howMany
Parameters:int[], int[], int
Returns:int
Method signature:int howMany(int[] connect1, int[] connect2, int numPeople)
(be sure your method is public)
    
 

Notes

-Without loss of generality, you can assume that the people are arranged in a circular pattern. Continuing this image, the base network would be seen from a helicopter as a circle.
 

Constraints

-connect1 must contain between 1 and 18 elements inclusive
-connect1 must contain the same number of elements as connect2
-numPeople must be between 4 and 10000 inclusive
-Element i of connect1 will not be equal to element i of connect2
-Each element of connect1 and connect2 will be between 0 and numPeople-1 inclusive
-There will be no repeated connections. In other words, if a connection from a to b exists, there will be no other connections of the form a to b or b to a allowed as input. This includes the original connections, so there will be no connections from i to i+1, or from 0 to the last person.
 

Examples

0)
    
{0,1}
{2,3}
4
Returns: 0
The given connections can easily be formed without crossings as depicted below:
  _______
 /       |
0---1   /
|  /|  / 
| / | /  
|/  |/   
3---2
1)
    
{4,4,4,5,5,6}
{6,7,8,7,8,8}
10
Returns: 1
There is no way for all of these connections to be added without a crossing.
2)
    
{0,2,4}
{3,5,1}
6
Returns: 1
3)
    
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18}
{2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20}
100
Returns: 0
4)
    
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17}
{30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47}
1000
Returns: 16

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SetComparison

String Parsing



Used in:

CRPF Charity Finals

Used as:

Division I Level Three

Writer:

brett1479

Testers:

lbackstrom , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1636

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4664&pm=1636

Problem Statement

    When studying set theory, the line between elements and sets is often blurred. Using the following definitions, you are going to write a function that will help students in a set theory class make such distinctions.



An atom is something that is not a set. In this problem atoms will be strings of lowercase letters.



A set is a collection of elements. The elements can be other sets, or atoms. In this problem, sets will be represented as comma-delimited lists of elements, the whole of which is enclosed in curly brackets ( '{' and '}' ). A set may be empty, and is thus denoted as "{}". This notation convention will be used throughout the rest of the problem statement.



x is a member of a set B if B contains x. For example, a, {b}, and {c,{a}} are all members of {a,{b},{c,{a}}}. b and {} are not members of this set.



Two sets are equivalent if and only if they contain exactly the same elements. Worded differently, two sets are NOT equivalent if there is an element contained by one that isn't contained by the other. For example, {a,{b},c}, {a,c,{b}}, and {a,a,{b},c} are all equivalent since they contain the same elements. The set {a,{b},c,b} is not equivalent to the previous three since none of them contain the element b. Note that duplication of elements does not affect a set.



A set A is a subset of a set B if and only if B contains every element that A contains and possibly others as well. For example, {}, {a,a,b}, {a,{c},b}, and {{c},a,b,c} are all subsets of {{c},a,c,b}. Note that {a,a,b} contains elements a and b, which are both contained in {{c},a,c,b}.



A set A is a proper subset of a set B if and only if A is a subset of B and they are not equivalent.



A set A is the powerset of a set B if and only if A contains every possible subset of B and nothing else. For example, {{a},{b},{a,b},{}} is the powerset of {a,b}. {a,{a},{}} is not the powerset of {a}.



A set A is equipotent to a set B if and only if A and B contain the same number of distinct elements. The word distinct here is only used for added emphasis. For example, {a,b,c}, {aa,bb,cc}, and {d,{e},f,f} are all equipotent to each other because they each contain 3 distinct elements. {a,a,a}, {a,b,c,{}} and {a,a,b} are not equipotent to the previous three.



Given 2 Strings a and b representing sets, your function will return a String[] containing each of the following that holds true for a and b:

"MEMBER" : if a is a member of b

"EQUIVALENT" : if a and b are equivalent

"SUBSET" : if a is a subset of b

"PROPER SUBSET" : if a is a proper subset of b

"POWERSET" : if a is the powerset of b

"EQUIPOTENT" : if a and b are equipotent

The returned String[] should be sorted in lexicographic ('A'-'Z') order.

 

Definition

    
Class:SetComparison
Method:relation
Parameters:String, String
Returns:String[]
Method signature:String[] relation(String a, String b)
(be sure your method is public)
    
 

Constraints

-a must contain between 2 and 50 characters inclusive
-b must contain between 2 and 50 characters inclusive
-Both a and b must adhere to the following grammar:

VALID = "{" LIST "}" | "{}"

LIST = ITEM | ITEM "," LIST

ITEM = VALID | ATOM

ATOM = positive length lowercase string
-Both a and b will only contain lowercase letters ('a'-'z'), brackets ('{' and '}'), and commas (',')
 

Examples

0)
    
"{}"
"{a,b,c,c,c,d,d,d}"
Returns: { "PROPER SUBSET",  "SUBSET" }
The empty set is always a subset of any set. Since a and b do not represent equivalent sets, it is a proper subset as well.
1)
    
"{{a,b},{a},{b},{}}"
"{a,b}"
Returns: { "POWERSET" }
Here the set represented by a contains every possible subset of the set represented by b.
2)
    
"{a,b,c,d,e}"
"{a,a,b,b,c,c,d,d,e,e}"
Returns: { "EQUIPOTENT",  "EQUIVALENT",  "SUBSET" }
Only difference is repeated elements.
3)
    
"{{a}}"
"{{{a}},{a}}"
Returns: { "MEMBER",  "PROPER SUBSET",  "SUBSET" }
4)
    
"{a,a,{a},{a},{a,a,a},{},{},a,aa}"
"{a,{a},{},aa}"
Returns: { "EQUIPOTENT",  "EQUIVALENT",  "SUBSET" }
5)
    
"{frank,bob}"
"{{},{frank,frank},{bob},{frank,bob,bob},{}}"
Returns: { "MEMBER" }
6)
    
"{{a,b},{a},{a,b},{},{b},{b,a}}"
"{a,b}"
Returns: { "POWERSET" }
7)
    
"{a,b,c,d}"
"{a,b}"
Returns: { }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Circuits

Graph Theory



Used in:

TCCC '03 Semifinals 4

Used as:

Division I Level One

Writer:

brett1479

Testers:

zoidal , lbackstrom

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1593

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4494&pm=1593

Problem Statement

    An essential part of circuit design and general system optimization is critical path analysis. On a chip, the critical path represents the longest path any signal would have to travel during execution. In this problem we will be analyzing chip designs to determine their critical path length. The chips in this problem will not contain any cycles, i.e. there exists no path from one component of a chip back to itself.



Given a String[] connects representing the wiring scheme, and a String[] costs representing the cost of each connection, your method will return the size of the most costly path between any 2 components on the chip. In other words, you are to find the longest path in a directed, acyclic graph. Element j of connects will list the components of the chip that can be reached directly from the jth component (0-based). Element j of costs will list the costs of each connection mentioned in the jth element of connects. As mentioned above, the chip will not contain any cyclic paths. For example:
connects = {"1 2",
            "2",
            ""}
costs    = {"5 3",
            "7",
            ""}
In this example, component 0 connects to components 1 and 2 with costs 5 and 3 respectively. Component 1 connects to component 2 with a cost of 7. All connections mentioned are directed. This means a connection from component i to component j does not imply a connection from component j to component i. Since we are looking for the longest path between any 2 components, your method would return 12.
 

Definition

    
Class:Circuits
Method:howLong
Parameters:String[], String[]
Returns:int
Method signature:int howLong(String[] connects, String[] costs)
(be sure your method is public)
    
 

Constraints

-connects must contain between 2 and 50 elements inclusive
-connects must contain the same number of elements as costs
-Each element of connects must contain between 0 and 50 characters inclusive
-Each element of costs must contain between 0 and 50 characters inclusive
-Element i of connects must contain the same number of integers as element i of costs
-Each integer in each element of connects must be between 0 and the size of connects-1 inclusive
-Each integer in each element of costs must be between 1 and 1000 inclusive
-Each element of connects may not contain repeated integers
-Each element of connects must be a single space delimited list of integers, each of which has no extra leading zeros. There will be no leading or trailing whitespace.
-Each element of costs must be a single space delimited list of integers, each of which has no extra leading zeros. There will be no leading or trailing whitespace.
-The circuit may not contain any cycles
 

Examples

0)
    
{"1 2",
 "2",
 ""}
{"5 3",
 "7",
 ""}
Returns: 12
From above
1)
    
{"1 2 3 4 5","2 3 4 5","3 4 5","4 5","5",""}
{"2 2 2 2 2","2 2 2 2","2 2 2","2 2","2",""}
Returns: 10
The longest path goes from 0-1-2-3-4-5 for a cost of 10.
2)
    
{"1","2","3","","5","6","7",""}
{"2","2","2","","3","3","3",""}
Returns: 9
The 0-1-2-3 path costs 6 whereas the 4-5-6-7 path costs 9
3)
    
{"","2 3 5","4 5","5 6","7","7 8","8 9","10",
 "10 11 12","11","12","12",""}
{"","3 2 9","2 4","6 9","3","1 2","1 2","5",
 "5 6 9","2","5","3",""}
Returns: 22
4)
    
{"","2 3","3 4 5","4 6","5 6","7","5 7",""}
{"","30 50","19 6 40","12 10","35 23","8","11 20",""}
Returns: 105

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

ChessMetric

Dynamic Programming, Graph Theory



Used in:

TCCC '03 Round 4

Used as:

Division I Level One

Writer:

brett1479

Testers:

lbackstrom , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1592

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4482&pm=1592

Problem Statement

    Suppose you had an n by n chess board and a super piece called a kingknight. Using only one move the kingknight denoted 'K' below can reach any of the spaces denoted 'X' or 'L' below:
   .......
   ..L.L..
   .LXXXL.
   ..XKX..
   .LXXXL.
   ..L.L..
   .......
In other words, the kingknight can move either one space in any direction (vertical, horizontal or diagonally) or can make an 'L' shaped move. An 'L' shaped move involves moving 2 spaces horizontally then 1 space vertically or 2 spaces vertically then 1 space horizontally. In the drawing above, the 'L' shaped moves are marked with 'L's whereas the one space moves are marked with 'X's. In addition, a kingknight may never jump off the board.



Given the size of the board, the start position of the kingknight and the end position of the kingknight, your method will return how many possible ways there are of getting from start to end in exactly numMoves moves. start and finish are int[]s each containing 2 elements. The first element will be the (0-based) row position and the second will be the (0-based) column position. Rows and columns will increment down and to the right respectively. The board itself will have rows and columns ranging from 0 to size-1 inclusive.



Note, two ways of getting from start to end are distinct if their respective move sequences differ in any way. In addition, you are allowed to use spaces on the board (including start and finish) repeatedly during a particular path from start to finish. We will ensure that the total number of paths is less than or equal to 2^63-1 (the upper bound for a long).
 

Definition

    
Class:ChessMetric
Method:howMany
Parameters:int, int[], int[], int
Returns:long
Method signature:long howMany(int size, int[] start, int[] end, int numMoves)
(be sure your method is public)
    
 

Notes

-For C++ users: long long is a 64 bit datatype and is specific to the GCC compiler.
 

Constraints

-size will be between 3 and 100 inclusive
-start will contain exactly 2 elements
-finish will contain exactly 2 elements
-Each element of start and finish will be between 1 and size-1 inclusive
-numMoves will be between 1 and 50 inclusive
-The total number of paths will be at most 2^63-1.
 

Examples

0)
    
3
{0,0}
{1,0}
1
Returns: 1
Only 1 way to get to an adjacent square in 1 move
1)
    
3
{0,0}
{1,2}
1
Returns: 1
A single L-shaped move is the only way
2)
    
3
{0,0}
{2,2}
1
Returns: 0
Too far for a single move
3)
    
3
{0,0}
{0,0}
2
Returns: 5
Must count all the ways of leaving and then returning to the corner
4)
    
100
{0,0}
{0,99}
50
Returns: 243097320072600

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GForce

Geometry, Search



Used in:

SRM 149

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1587

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4550&pm=1587

Problem Statement

     A primary limitation of fighter plane performance is the ability of the pilot to remain conscious. We have determined that pilots can withstand large accelerations for short time periods, but that they cannot handle an extended time period during which the average acceleration is high.

Create a class GForce that contains a method avgAccel that will be given the period as an int, and int[]'s accel and time giving a piecewise-linear approximation to the acceleration experienced over time during a flight. The method will return the greatest average acceleration experienced over any interval of length equal to period. The return value should be the average acceleration as a double.

The piecewise-linear acceleration function is given in order of increasing times, starting with the beginning of the flight and ending at the end of the flight. The graph of acceleration versus time is the sequence of straight-line segments joining adjacent points (timei, acceli).

The average acceleration over an interval is the area under the graph between the beginning and ending times, divided by the length of the interval.

 

Definition

    
Class:GForce
Method:avgAccel
Parameters:int, int[], int[]
Returns:double
Method signature:double avgAccel(int period, int[] accel, int[] time)
(be sure your method is public)
    
 

Notes

-The returned result must only be relatively close to the correct answer. Specifically, if the returned value either has a relative error or an absolute error less than 10^-9 it is accepted as correct.
 

Constraints

-accel contains between 2 and 50 elements inclusive
-time contains the same number of elements as accel
-the elements of time are strictly increasing
-the elements of time and of accel are between 0 and 10,000 inclusive
-period is greater than 0 and less than the difference between the first and last elements of time
 

Examples

0)
    
100
{1500,1500,500,2000}
{0,100,150,225}
Returns: 1500.0
 accel                        
  2000 +            X   
  1500 +   X---X   /    
  1000 +        \ /   
   500 +         X                          
       +-+-+-+-+-+-+-+-+-+---- time
     -100  0  100 200 300
The four points determine a piecewise linear function with three segments, whose graph is shown. The interval from 0 to 100 is the one with the biggest average accel. In this region the average is obviously 1500.

The highest accel value is at t=225, but if we compute the area under the curve between 125 and 225 we get 112,500 so the average on that interval is 1125 which is not as high as 1500.

1)
    
500
{5,30,5}
{0,1000,2000}
Returns: 26.875
By symmetry the interval with the highest average must be 750 to 1250. The area under the curve in this interval consists of two trapezoids, each with width 250 and heights 23.75 and 30. The sum of their areas is 26.875.
2)
    
11
{0,5,5,0,6}
{0,5,15,25,31}
Returns: 4.984848484848485

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

DesertWind

Dynamic Programming, Graph Theory



Used in:

SRM 164

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1570

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4625&pm=1570

Problem Statement

    The Desert. Failing water, dying camels, howling wind. The desert wind has hands -- it throws sand in your face, pushes you down, tries to bury you.

We are stranded in the desert. But we have a map showing where we are, where all the impassable terrain is located, and where every oasis is located. The map is divided into square cells, and our trip will be a sequence of legs, where each leg goes from one cell to one of the 8 adjacent cells. We must start at our current location and make it to an oasis, any oasis. Of course, we cannot use any impassable cell and cannot leave the mapped area. Our survival depends on how many days it will take to make the journey.

That evil Desert Wind is our nemesis! Each leg takes one day unless we are traveling directly against the wind. In that case the leg will take three days. Fortunately, the wind's direction can be determined just before setting out on a leg and will not change for at least a day.

Create a class DesertWind that contains the method daysNeeded that takes a String[] theMap and returns the number of days required, assuming the worst possible wind conditions will occur. Return -1 if no path to an oasis exists.

Each element of theMap gives the terrain for the cells (in west to east order) at a particular latitude; the first element is the most northern, the last element is the most southern on the map. Each cell is indicated by a single character:

  • '*' is an oasis
  • 'X' is impassable
  • '@' is the starting location
  • '-' is sand

 

Definition

    
Class:DesertWind
Method:daysNeeded
Parameters:String[]
Returns:int
Method signature:int daysNeeded(String[] theMap)
(be sure your method is public)
    
 

Constraints

-theMap has between 2 and 50 elements inclusive, each having the same length
-the length of each element of theMap is between 2 and 50 inclusive
-'@' appears exactly once in exactly one element of theMap
-each element of theMap contains only the characters '*','-','X','@'
 

Examples

0)
    
{"--*","@-*","X--"}
Returns: 2
   - - *
   @ - *
   X - -
No matter how the wind is blowing we can make it to one of the two northernmost cells in the second column in one day. Whichever cell we reach and whichever way the wind is blowing the second day, we can get to an oasis without heading into the wind.
1)
    
{"-X-*","-@X-","---X","--**"}
Returns: 3
   - X - *
   - @ X -
   - - - X
   - - * *
Unless the wind is from the southeast, we will go southeast on the first day, and then will have two different directions that lead to an oasis -- one of them will not be against the wind so we will reach an oasis in 2 days. But if the wind is from the southeast on the first day, we will go south. Then, if the wind is from the southeast on the second day we will go east (otherwise we can go southeast to an oasis). Now we can reach one of the two oases on the third day, no matter how the wind blows.

There is no way to reach the northeast oasis in less than 4 days if the wind is evil. Even if the first day the wind is not from the northeast, it would be a fatal mistake to go that direction.

2)
    
{"*--X-----",
 "--XX--@--",
 "*-X------"}
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Macros

Dynamic Programming



Used in:

TCCC '03 Round 2

Used as:

Division I Level Three

Writer:

brett1479

Testers:

lbackstrom , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1526

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4472&pm=1526

Problem Statement

    You have been working with a macro processor that has rules of the following form:
   VarChar : VarOrTextChar VarOrTextChar
   where VarChar is an uppercase letter, 
   and VarOrTextChar is an uppercase or lowercase letter
The macro processor only recognizes 2 kinds of characters, namely Variable Characters (uppercase letters) and Text Characters (lowercase letters). If it finds a Variable Character in the text that matches the left side of one of its rules it can replace it with the characters on the right side of that rule. If more than one rule has a left side that matches, the processor can arbitrarily choose which rule to use. This process continues until the processor gets rid of all the Variable Characters. For example, let's say the processor had the following rules:
rules = {"S:aA",
         "A:Sb",
         "S:ab",
	 "D:aA"}
Then given the string "S" it could do the following actions:

S => replace S with aA => aA => replace A with Sb => aSb => replace S with ab => aabb

or perhaps

S => replace S with ab => ab.

These are just two possible sequences of actions out of an infinite number of possible sequences that the processor could follow with the above rules. Our problem is, we have only been given the output and are clueless as to the initial input. Given the rules of the processor, and the output text, your method will return all of the Variable Characters that could have produced the given output, in lexicographic ('A' to 'Z') order. Using the rules in the above example, if given output "aabb", your method would return {"D","S"}.
 

Definition

    
Class:Macros
Method:whichOnes
Parameters:String[], String
Returns:String[]
Method signature:String[] whichOnes(String[] rules, String output)
(be sure your method is public)
    
 

Constraints

-rules will contain between 1 and 50 elements, inclusive.
-Each element of rules will have 4 characters.
-The first character of each element of rules will be an uppercase letter ('A'-'Z').
-The second character of each element of rules will be a colon (':').
-The third and fourth characters of each element of rules will be uppercase or lowercase letters ('A'-'Z','a'-'z').
-output will have between 2 and 50 characters, inclusive.
-output will contain only lowercase letters ('a'-'z').
 

Examples

0)
    
{"S:aA",
 "A:Sb",
 "S:ab",
 "D:aA"}
"aabb"
Returns: { "D",  "S" }
This is the example from the problem statement.
1)
    
{"S:aA",
 "A:Sb",
 "S:ab",
 "D:aA"}
"ab"
Returns: { "S" }
The only way to produce "ab" is to start with "S" and immediately replace "S" with "ab", using the third rule.
2)
    
{"S:aA",
 "A:Sb",
 "S:ab",
 "D:aA"}
"aaaaabbbb"
Returns: { }
3)
    
{"A:aB",
 "C:dE",
 "Z:FG",
 "B:dd"}
"qqqq"
Returns: { }
4)
    
{"A:aB",
 "C:dE",
 "Z:FG",
 "B:dd"}
"add"
Returns: { "A" }
5)
    
{"A:BC",
 "B:BC",
 "C:BC",
 "B:aa",
 "C:bb"}
"aaaaaaaaaabbbbbbbbbb"
Returns: { "A",  "B",  "C" }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Marketing

Graph Theory



Used in:

TCCC '03 Round 2

Used as:

Division I Level Two

Writer:

brett1479

Testers:

lbackstrom , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1524

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4472&pm=1524

Problem Statement

    You work for a very large company that markets many different products. In some cases, one product you market competes with another. To help deal with this situation you have split the intended consumers into two groups, namely Adults and Teenagers. If your company markets 2 products that compete with each other, selling one to Adults and the other to Teenagers will help maximize profits. Given a list of the products that compete with each other, you are going to determine whether all can be marketed such that no pair of competing products are both sold to Teenagers or both sold to Adults. If such an arrangement is not feasible your method will return -1. Otherwise, it should return the number of possible ways of marketing all of the products.



The products will be given in a String[] compete whose kth element describes product k. The kth element will be a single-space delimited list of integers. These integers will refer to the products that the kth product competes with. For example:
compete = {"1 4",
            "2",
            "3",
            "0",
	    ""}
The example above shows product 0 competes with 1 and 4, product 1 competes with 2, product 2 competes with 3, and product 3 competes with 0. Note, competition is symmetric so product 1 competing with product 2 means product 2 competes with product 1 as well.

Ways to market:

1) 0 to Teenagers, 1 to Adults, 2 to Teenagers, 3 to Adults, and 4 to Adults

2) 0 to Adults, 1 to Teenagers, 2 to Adults, 3 to Teenagers, and 4 to Teenagers

Your method would return 2.
 

Definition

    
Class:Marketing
Method:howMany
Parameters:String[]
Returns:long
Method signature:long howMany(String[] compete)
(be sure your method is public)
    
 

Constraints

-compete will contain between 1 and 30 elements, inclusive.
-Each element of compete will have between 0 and 50 characters, inclusive.
-Each element of compete will be a single space delimited sequence of integers such that:
  • All of the integers are unique.
  • Each integer contains no extra leading zeros.
  • Each integer is between 0 and k-1 inclusive where k is the number of elements in compete.
-No element of compete contains leading or trailing whitespace.
-Element i of compete will not contain the value i.
-If i occurs in the jth element of compete, j will not occur in the ith element of compete.
 

Examples

0)
    
{"1 4","2","3","0",""}
Returns: 2
The example from above.
1)
    
{"1","2","0"}
Returns: -1
Product 0 cannot be marketed with product 1 or 2. Product 1 cannot be marketed with product 2. There is no way to achieve a viable marketing scheme.
2)
    
{"1","2","3","0","0 5","1"}
Returns: 2
3)
    
{"","","","","","","","","","",
 "","","","","","","","","","",
 "","","","","","","","","",""}
Returns: 1073741824
4)
    
{"1","2","3","0","5","6","4"}
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

MessageMess

Dynamic Programming, Encryption/Compression



Used in:

SRM 149

Used as:

Division I Level Two

Writer:

dgoodman

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1331

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4550&pm=1331

Problem Statement

    It is a common practice in cryptography to remove the spaces from a message before encoding it to help to disguise its structure. Even after it is then decoded, we are left with the problem of putting the spaces back in the message.

Create a class MessageMess that contains a method restore that takes a String[] dictionary of possible words and a String message as inputs. It returns the message with single spaces inserted to divide the message into words from the dictionary. If there is more than one way to insert spaces, it returns "AMBIGUOUS!" If there is no way to insert spaces, it returns "IMPOSSIBLE!" The return should never have any leading or trailing spaces.

 

Definition

    
Class:MessageMess
Method:restore
Parameters:String[], String
Returns:String
Method signature:String restore(String[] dictionary, String message)
(be sure your method is public)
    
 

Notes

-Don't forget the '!' at the end of the two special returns
-A proper message may require 0 spaces to be inserted
 

Constraints

-dictionary will contain between 1 and 50 elements inclusive
-the elements of dictionary will be distinct
-each element of dictionary will contain between 1 and 50 characters
-message will contain between 1 and 50 characters
-every character in message and in each element of dictionary will be an uppercase letter 'A'-'Z'
 

Examples

0)
    
{"HI", "YOU", "SAY"}
"HIYOUSAYHI"
Returns: "HI YOU SAY HI"
A word from dictionary may appear multiple times in the message.
1)
    
{"ABC", "BCD", "CD", "ABCB"}
"ABCBCD"
Returns: "AMBIGUOUS!"
"ABC BCD" and "ABCB CD" are both possible interpretations of message.
2)
    
{"IMPOSS", "SIBLE", "S"}
"IMPOSSIBLE"
Returns: "IMPOSSIBLE!"
There is no way to concatenate words from this dictionary to form "IMPOSSIBLE"
3)
    
{"IMPOSS", "SIBLE", "S", "IMPOSSIBLE"}
"IMPOSSIBLE"
Returns: "IMPOSSIBLE"
This message can be decoded without ambiguity. This requires the insertion of no spaces since the entire message appears as a word in the dictionary.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

SkewHeaps

Search



Used in:

TCO '03 Semifinals 2

Used as:

Division I Level Three

Writer:

vorthys

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1318

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4707&pm=1318

Problem Statement

    

Skew heaps are an excellent implementation of priority queues. A skew heap is a binary tree like a binary search tree, but with a different ordering of its elements. In a skew heap, the elements are heap-ordered, meaning that every child is larger than its parent. A left sibling is not required to be smaller than its right sibling, and skew heaps are not required to be balanced. The heap-ordering property implies that the minimum element in a skew heap is always the root.

Inserting a new element X into a skew heap H is done recursively. The base case applies when H is empty or when X is smaller than the existing root. The new element becomes the new root, with the old root as its left child. The recursive case applies when X is larger than the existing root. The left and right subtrees of the existing root are swapped, and X is inserted recursively into the left subtree (which was the right subtree before the swap). These two cases are illustrated below.


     BASE CASE (H is empty or X < root of H)
     ---------------------------------------
       Insert(X, H) ===>   X
                          /
                         H

     RECURSIVE CASE (X > Y)
     ---------------------------------------
       Insert(X,  Y  ) ===>            Y
                 / \                  / \
                A   B       Insert(X,B)  A

The following snapshots show the results of sequentially inserting the numbers 0,1,2,3,4,5,6 into an initially empty tree (where all children not shown are assumed to be null):


      0    0    0        0        0         0           0
          /    / \      / \      / \       / \         / \
         1    2   1    1   2    2   1     /   \       /   \
                      /        /   /     1     2     2     1
                     3        4   3     / \   /     / \   / \
                                       5   3 4     6   4 5   3
Notice how, because of the swaps, new elements are distributed evenly between the two sides of the tree. In this case, the odd elements (1,3,5) are placed on one side of the tree, and the non-zero even elements (2,4,6) are placed on the other side of the tree.

On the other hand, it is also possible to get an unbalanced tree if the elements are not inserted in sorted order. For example, sequentially inserting the numbers 6,4,5,2,0,1,3 into an initially empty tree yields


      6    4    4        2        0     0         0
          /    / \      /        /     / \       / \
         6    5   6    4        2     1   2     2   1
                      / \      /         /     / \
                     5   6    4         4     3   4
                             / \       / \       / \
                            5   6     5   6     5   6
Notice how elements inserted after the overall minimum element are distributed evenly between the left and right subtrees of the root (e.g., 1 and 3 in the last tree above). In contrast, elements inserted before the overall minimum element end up in the same subtree of the root (e.g., 6, 4, 5, and 2 above).

Your task is to write a method that will take a skew heap and return the sequence of insertions that might have created that heap. If more than one sequence of insertions might have created the final skew heap, return the lexicographically earliest. A sequence A is lexicographically earlier than a sequence B if the element of A at the leftmost position at which the sequences differ is smaller than the element of B at the same position.

The input heap contains the values 0 through n-1, inclusive, where n is the size of the heap. Each value appears exactly once in the heap. The shape of the input tree will be represented by a int[], parent, of size n-1. If the node containing i is a left child, then element i-1 of parent is the value of the node's parent. If the node containing i is a right child, then element i-1 of parent is 100 plus the value of the parent. Note that parent is 0-indexed. The node containing 0 is always the root, so its parent is not represented. For example, the skew heap

              0
             / \
            1   2
           /   / \
          5   4   3
would be represented by parent = {0,100,102,2,1}, meaning that
  • 1 is the left child of 0.
  • 2 is the right child of 0.
  • 3 is the right child of 2.
  • 4 is the left child of 2.
  • 5 is the left child of 1.

No skew heap built entirely by inserts will ever contain a node with an empty left subtree and a non-empty right subtree. Such heaps will not be permitted as input.

 

Definition

    
Class:SkewHeaps
Method:history
Parameters:int[]
Returns:int[]
Method signature:int[] history(int[] parent)
(be sure your method is public)
    
 

Constraints

-parent contains between 1 and 50 elements, inclusive.
-Element i of parent is either between 0 and i, inclusive, or between 100 and 100+i, inclusive.
-No value appears more than once in parent.
-If the value 100+k appears in parent, for some non-negative k, then the value k must also appear in parent.
 

Examples

0)
    
{ 100, 0, 101, 102, 1, 2 }
Returns: { 0,  1,  2,  3,  4,  5,  6 }
The tree
        0
       / \
      /   \
     2     1
    / \   / \
   6   4 5   3
1)
    
{ 100, 0, 2, 102, 4, 104 }
Returns: { 4,  6,  5,  2,  0,  1,  3 }
The tree
        0
       / \
      2   1
     / \
    3   4
       / \
      5   6
Either {4,6,5,2,0,1,3} or {6,4,5,2,0,1,3} could have created this tree, so we return the lexicographically smallest.
2)
    
{ 0, 100, 1, 102, 2, 3, 5 }
Returns: { 2,  5,  0,  3,  4,  6,  7,  1 }
The tree
        0
       / \
      1   2
     /   / \
    3   5   4
   /   /
  6   7
There are eight sequences that could have produced this tree:
  {2,5,0,3,4,6,7,1}
  {2,5,0,6,4,3,7,1}
  {2,7,0,3,4,6,5,1}
  {2,7,0,6,4,3,5,1}
  {5,2,0,3,4,6,7,1}
  {5,2,0,6,4,3,7,1}
  {7,2,0,3,4,6,5,1}
  {7,2,0,6,4,3,5,1}
We choose the lexicographically smallest.
3)
    
{ 0 }
Returns: { 0,  1 }
The tree
        0
       /
      1
4)
    
{ 100, 1, 101, 103, 3, 4, 6, 107, 7, 0, 10, 11, 110, 12, 112, 111, 8, 108, 2, 16 }
Returns: 
{ 8,  18,  17,  7,  9,  0,  11,  6,  12,  4,  16,  3,  15,  1,  20,  2,  10,  5,  13,  19,  14 }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Escape

Graph Theory, Search



Used in:

TCI '02 Semifinals 2

Used as:

Division I Level Two

Writer:

brett1479

Testers:

alexcchan , lbackstrom

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1170

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4371&pm=1170

Problem Statement

    You are playing a video game that involves escaping from a dangerous area. Within the area there are DEADLY regions you can't enter, HARMFUL regions that take 1 life for every step you make in them, and NORMAL regions that don't affect you in any way. You will start from (0,0) and have to make it to (500,500) using only Up, Left, Right, and Down steps. The map will be given as a String[] deadly listing the DEADLY regions and a String[] harmful listing the HARMFUL regions. The elements in each of these parameters will be formatted as follows:

Input format(quotes for clarity): "X1 Y1 X2 Y2" where

(X1,Y1) is one corner of the region and

(X2,Y2) is the other corner of the region

The corners of the region are inclusive bounds (i.e. (4,1) and (2,2) include x-values between 4 and 2 inclusive and y-values between 1 and 2 inclusive). All unspecified regions are considered NORMAL. If regions overlap for a particular square, then whichever region is worst takes effect (e.g. DEADLY+HARMFUL = DEADLY, HARMFUL+NORMAL = HARMFUL, HARMFUL+HARMFUL = HARMFUL, DEADLY+NORMAL=DEADLY).

Damage taken at each step occurs based on the destination square and not on the starting square (e.g. if the square (500,500) is HARMFUL you WILL take a point of damage stepping onto it; if the square (0,0) is HARMFUL you WON'T take a point of damage stepping off of it; this works analogously for DEADLY squares).

Return the least amount of life you will have to lose in order to reach the destination. Return -1 if there is no path to the destination. Your character is not allowed to leave the map (i.e. have X or Y less than 0 or greater than 500).

 

Definition

    
Class:Escape
Method:lowest
Parameters:String[], String[]
Returns:int
Method signature:int lowest(String[] harmful, String[] deadly)
(be sure your method is public)
    
 

Notes

-If two harmful regions overlap, the area where they overlap is exactly the same as non-overlapping harmful regions (i.e. the effect is NOT cumulative, and the overlapping region still takes exactly 1 life)
 

Constraints

-deadly will contain between 0 and 50 elements inclusive
-harmful will contain between 0 and 50 elements inclusive
-Each element of deadly and harmful will be of the form (quotes for clarity): "X1 Y1 X2 Y2"

where X1,Y1,X2, and Y2 are integers between 0 and 500 inclusive and contain no leading zeros
-Each element of deadly and harfmul will contain no leading, trailing or extra whitespace
 

Examples

0)
    
{}
{}
Returns: 0
There are no DEADLY or HARMFUL regions.
1)
    
{"500 0 0 500"}
{"0 0 0 0"}
Returns: 1000
(0,0) is DEADLY but that doesn't affect our path since we never step onto it (only from it). The rest of the map is NORMAL.
2)
    
{"0 0 250 250","250 250 500 500"}
{"0 251 249 500","251 0 500 249"}
Returns: 1000
Just enough space to get around the DEADLY regions.
3)
    
{"0 0 250 250","250 250 500 500"}
{"0 250 250 500","250 0 500 250"}
Returns: -1
No way around the DEADLY regions.
4)
    
{"468 209 456 32",
 "71 260 306 427",
 "420 90 424 492",
 "374 253 54 253",
 "319 334 152 431",
 "38 93 204 84",
 "246 0 434 263",
 "12 18 118 461",
 "215 462 44 317",
 "447 214 28 475",
 "3 89 38 125",
 "157 108 138 264",
 "363 17 333 387",
 "457 362 396 324",
 "95 27 374 175",
 "381 196 265 302",
 "105 255 253 134",
 "0 308 453 55",
 "169 28 313 498",
 "103 247 165 376",
 "264 287 363 407",
 "185 255 110 415",
 "475 126 293 112",
 "285 200 66 484",
 "60 178 461 301",
 "347 352 470 479",
 "433 130 383 370",
 "405 378 117 377",
 "403 324 369 133",
 "12 63 174 309",
 "181 0 356 56",
 "473 380 315 378"}
{"250 384 355 234",
 "28 155 470 4",
 "333 405 12 456",
 "329 221 239 215",
 "334 20 429 338",
 "85 42 188 388",
 "219 187 12 111",
 "467 453 358 133",
 "472 172 257 288",
 "412 246 431 86",
 "335 22 448 47",
 "150 14 149 11",
 "224 136 466 328",
 "369 209 184 262",
 "274 488 425 195",
 "55 82 279 253",
 "153 201 65 228",
 "208 230 132 223",
 "369 305 397 267",
 "200 145 98 198",
 "422 67 252 479",
 "231 252 401 190",
 "312 20 0 350",
 "406 72 207 294",
 "488 329 338 326",
 "117 264 497 447",
 "491 341 139 438",
 "40 413 329 290",
 "148 245 53 386",
 "147 70 186 131",
 "300 407 71 183",
 "300 186 251 198",
 "178 67 487 77",
 "98 158 55 433",
 "167 231 253 90",
 "268 406 81 271",
 "312 161 387 153",
 "33 442 25 412",
 "56 69 177 428",
 "5 92 61 247"}
Returns: 254

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

GraphPaths

Dynamic Programming, Graph Theory



Used in:

TCI '02 Semifinals 1

Used as:

Division I Level Two

Writer:

brett1479

Testers:

alexcchan , lbackstrom

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1168

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4370&pm=1168

Problem Statement

    You will be given a String[] representing a directed graph. Each element will be formatted as follows:

Node1 Node2 Node3 ...

where NodeJ is a number (0-indexed) representing a node. Element K of the String[] graph will list all of the nodes that node K has a directed edge to. For example:
graph = {"1 2 3",
	 "0 1 2",
	 "0",
	 "1 2"}
Represents a directed graph where:

node 0 has a directed edge to nodes 1, 2, and 3,

node 1 has a directed edge to nodes 0, 1 and 2,

node 2 has a directed edge to node 0, and

node 3 has a directed edge to nodes 1 and 2.

Given a String[] formatted as above representing the directed graph, an int representing the starting node, an int representing the destination node, and an int representing the path length, determine how many unique paths exist from the starting node to the destination node of the specified length. Note, the paths may contain cycles. The length of a path is how many edges it traverses, possibly counting an edge more than once if the path contains a cycle.

If the total number of paths is greater than 2^63-1 (the limit of a long), return -1

 

Definition

    
Class:GraphPaths
Method:howMany
Parameters:String[], int, int, int
Returns:long
Method signature:long howMany(String[] graph, int start, int destination, int length)
(be sure your method is public)
    
 

Notes

-Two paths are unique if they differ at any node. For example: A->B->C->B is unique from A->C->B->B which are both unique from A->B->B->C.
 

Constraints

-graph will contain between 1 and 50 elements inclusive
-Each element of graph will have length between 1 and 50 inclusive
-Each element of graph will be a single-space delimited string of zero or more integers with no leading zeros
-Each element of graph will contain no leading or trailing whitespace
-Each integer in each element of graph will be between 0 and (size of graph - 1) inclusive where size of graph is the number of elements in graph
-Each element of graph will not contain any repeated integers
-start will be between 0 and (size of graph - 1) inclusive
-destination will be between 0 and (size of graph - 1) inclusive
-length will be between 1 and 1,000,000,000 inclusive
 

Examples

0)
    
{"1 2 3",
 "0 1 2",
 "0",
 "1 2"}
0
1
2
Returns: 2
1)
    
{
"1",
"2",
"3",
"4",
"5",
"0 3"
}
0
0
10000001
Returns: 0
Note that all paths from 0 to 0 have length divisible by 3.
2)
    
{
"1 2",
"0",
"0"
}
0
0
126
Returns: -1
The actual answer to this is 2^63, but that is outside of the range for a long, so we return -1.
3)
    
{"0 1 2 3", "0 1 2 3", "0 1 2 3", "0 1 2 3"} 
2
2
63
Returns: -1
4)
    
{"0"}
0
0
1
Returns: 1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Permutation

Graph Theory, Math, String Manipulation



Used in:

SRM 160

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1135

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4605&pm=1135

Problem Statement

    A permutation of the letters in an alphabet can be described by a string that contains each letter exactly once. For example, CABD describes the permutation of ABCD that maps A to C, B to A, C to B, and D to D. If we repeatedly apply that permutation, we will get the sequence ABCD,CABD,BCAD,ABCD,CABD,BCAD,ABCD,... This permutation is cyclic with length 3.

We want to find the permutation of the first n letters of

    ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
that has the longest cycle. Create a class Permutation that contains the method best that takes the number of characters n as input and returns the lexicographically first permutation that has the maximum possible cycle length.

"Lexicographically first" means the String that would sort first among all the permutations of maximum cycle length, using the ASCII sequence (which sorts uppercase letters before lowercase letters).

 

Definition

    
Class:Permutation
Method:best
Parameters:int
Returns:String
Method signature:String best(int n)
(be sure your method is public)
    
 

Constraints

-n is between 1 and 52 inclusive
 

Examples

0)
    
6
Returns: "ACBEFD"
This permutation has cycle length 6. So does BDEFCA, but ACBEFD is lexicographically first. The cycle is: ABCDEF -> ACBEFD -> ABCFDE -> ACBDEF -> ABCEFD -> ACBFDE -> ABCDEF
1)
    
7
Returns: "BCAEFGD"
This is the lexicographically first permutation with cycle length 12
2)
    
29
Returns: "BCDEAGHIJKLFNOPQRSTMVWXYZabcU"
3)
    
1
Returns: "A"
4)
    
8
Returns: "BCAEFGHD"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

HigherMaze

Graph Theory



Used in:

TCI '02 Semifinals 1

Used as:

Division I Level Three

Writer:

lars2520

Testers:

alexcchan , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1131

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4370&pm=1131

Problem Statement

    

We all know that there are not necessarily three dimensions, and that there are wormholes scattered throughout the universe which will transport you through time and space. However, because it is often difficult for people to conceptualize higher dimensions, we will probably have to have computers do most of our navigation for us. Your task is to write a program that will simulate a pseudo-random asteroid field, and then navigate a ship through the asteroid field as quickly as possible.

The first step will be to generate the asteroid field. You will be given a int[], dim, that will specify how large you should make each dimension in your asteroid field. For example, if dim is {3,4,5}, the generated asteroid field will be a 3 x 4 x 5 box, with corners at (0,0,0) and (2,3,4). If dim is {3,4,5,4}, the generated asteroid field will be a 3 x 4 x 5 x 4 hyper-box (a hyper box is analogous to a regular box, but in more than three dimensions). Then, you must determine which spaces in the asteroid field actually contain asteroids. This will be done pseudo-randomly using something like the following code, where a and p are inputs (remember that there are a variable number of dimensions):

int current = 1;
for(int i0 = 0; i0<dim0; i0++)
for(int i1 = 0; i1<dim1; i1++)
... one loop per dimension
{
    current = (current*a)%p;
    if((current&1)==1){
        //add an asteroid at (i0,i1,i2,...)
    }
}

Once the asteroid field is generated, you have to navigate through it. You will be given a int[], start, and a int[], finish. You must find your way through the asteroid field, as quickly as possible without running into an asteroid. You may move from any location (a0,a1,a2...) to any other location, (b0,b1,b2...) so long as for all i, the differences between ai and bi is either 1 or 0, and bi is between 0 and dimi-1, inclusive. Each such movement takes one unit of time. For example, if you were at the S below, you could move to any of the locations marked with T, where '.' represents open space.

.....
.TTT.
.TST.
.TTT.
.....

In addition to this type of movement, you may also (but are not required to) travel through wormholes. You will be given a String[], wormholes, which specifies the origin, length of time travel, and destination of some wormholes. To go through a wormhole, you must first reach the origin of the wormhole. Then, after going through the wormhole, you will be transported to the destination of the wormhole. Additionally, wormholes transport you in time. So, each wormhole has a fixed amount of time travel associated with it, and each time you go through the wormhole, you will go forward or backward in time by that amount. Each element of wormholes will be formatted as "<origin> <time> <destination>", where <origin> and <destination> and coordinates as a space delimited list. For example, "0 0 -1 3 7" would represent a wormhole that starts at (0,0), transports you back in time 1 unit, and leaves you at (3,7) in space. Thus, if you reached (0,0) 5 units of time after you started, it would be possible to reach (3,7) from there 4 units of time after you started.

Sometimes, it will be impossible to reach finish from start. In this case return, 2^31-1 = 2147483647.

 

Definition

    
Class:HigherMaze
Method:navigate
Parameters:int, int, int[], int[], int[], String[]
Returns:int
Method signature:int navigate(int a, int p, int[] dim, int[] start, int[] finish, String[] wormholes)
(be sure your method is public)
    
 

Constraints

-The product of all the elements of dim will be between 2 and 1000, inclusive.
-Each element of dim will be between 2 and 20, inclusive.
-dim will contain between 1 and 5 elements, inclusive.
-a and p will be between 1 and 2,000,000,000, inclusive.
-a times p will be between 1 and 2,000,000,000, inclusive.
-start and finish will be within the hyper-box defined by dim.
-start and finish will be both be empty space (not an asteroid, possibly a wormhole).
-wormholes will contain between 0 and 50 elements, inclusive.
-Each element of wormholes will be formatted as "<origin> <time> <destination>".
-<origin> and <destination> will both be space delimited (no extra, leading or trailing spaces) lists of integers, representing a coordinate in space within the hyper-box defined by dim.
-<origin> and <destination> will both be empty space (not an asteroid).
-<time> will be an integer in the range -1,000,000 to 1,000,000.
-There will be no way to go back in time infinitely. (In other words, there will be no reachable cycles that take negative amounts of time. However, there may be unreachable ones, but they can not affect the return, since they are unreachable.)
 

Examples

0)
    
138
193
{5,5}
{0,0}
{4,4}
{}
Returns: 6
This input generates the following two dimensional asteroid field, where an 'X' is an asteroid, and a '.' is open space. (Here, (0,0) is the upper left corner, and (4,4) is the lower right, and (4,0) is in the lower left):
...XX
XX.X.
..XXX
....X
.XXX.
Here is one path that takes 6 time units, where 'S' represents the start, 'F' the finish, and '*' the path.
S*.XX
XX*X.
.*XXX
..**X
.XXXF
1)
    
138
193
{5,5}
{0,0}
{4,4}
{"0 0 2 4 4"}
Returns: 2
While there is still a path from (0,0) to (4,4) which takes 6 time units, there is also a wormhole, which transports you directly from (0,0) to (4,4), and ahead 2 units of time.
2)
    
138
193
{5,5}
{0,0}
{4,4}
{"0 0 2 4 4","0 0 8 1 4","0 2 5 1 4","1 4 -8 4 4"}
Returns: -1
This is the same asteroid configuration as the previous two examples, but now there are more wormholes. The quickest way to get from (0,0) to (4,4) is to move from from (0,0) to (0,2), which takes 2 units of time. From (0,2) we should go through the wormhole to (1,4), which transports us ahead 5 units of time, for a total of 7. Then, we can take the wormhole from (1,4) to (4,4), which takes us back 8 units of time. Thus, the total time for the trip is 2 + 5 - 8 = -1, and we arrive before we left!

(note that two wormholes can start at the same location, and could even start and end at the same location)
3)
    
54
73
{20,20}
{1,2}
{12,12}
{}
Returns: 23
4)
    
139
193
{20,20}
{0,2}
{18,19}
{"0 2 -100000 0 19","4 18 -100000 7 0","8 0 1000000 19 10","19 6 -800000 13 8"}
Returns: 21
The only way to get all the way is to go through all 4 wormholes, in order.
5)
    
138
193
{5,5}
{0,0}
{4,0}
{"0 0 -6 4 4"}
Returns: -2
6)
    
139
193
{20}
{2}
{19}
{}
Returns: 2147483647

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Wireless

Geometry, Graph Theory



Used in:

TCI '02 Round 1 A

Used as:

Division I Level Three

Writer:

brett1479

Testers:

alexcchan , lbackstrom

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1124

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4324&pm=1124

Problem Statement

    In a wireless network, the distance between nodes determines connectivity and latency. The further apart two nodes are the slower the connection. If two nodes are further apart than the maximum allowable range they cannot directly communicate. In our network, there will be 2 kinds of nodes: stationary and roaming. When a roaming node wants to communicate with another roaming node it must first communicate with one of the stationary nodes in its range. The stationary node it connects to will then send the transmission through as many stationary nodes as are necessary before finally sending to the destination roaming node. In other words, the transmission always starts at a roaming node, goes through one or more stationary nodes, and finally arrives at the destination roaming node. For example:
R = roaming, S = stationary
.......--R......
....../.........
.....S--........
........\.......
.........S......
.........|......
..R--.../.......
.....\-S........
Above is one possible route between the two depicted roaming nodes.
In this problem you will be given the initial positions of the roaming nodes and their initial velocities. Each roaming node will either be moving upward, leftward, rightward, or downward at the rate of one square per second. For example:
roamNodes Input Format: Direction X Y
roamNodes = {"UP 9 0","DOWN 2 6"}
statNodes Input Format: X Y
statNodes = {"5 2","9 4","7 7"}
      Time 0                  Time 1                  Time 2
 0123456789012345        0123456789012345        0123456789012345
0.......--R......       0................       0................
1....../.........       1....../--R......       1................
2.....S--........       2.....S..........       2.....S...R......
3........\.......       3..../...........       3.........|......
4.........S......       4.../.....S......       4..R------S......
5.........|......       5..R.............       5................
6..R--.../.......       6................       6................
7.....\-S........       7.......S........       7.......S........
Above are the positions of the nodes, and some possible routes.
We are going to assume that the routing protocol will always choose the shortest possible end-to-end (roaming node-to-roaming node) route when connecting two roaming nodes. You will be given the wireless range of all nodes, the positions and velocities of the roaming nodes, and the positions of the stationary nodes. You will determine the length of the shortest route that will ever occur between the two roaming nodes in the system at any non-negative integral time. The distance between two nodes is always measured using the cartesian distance formula: sqrt((x2-x1)^2 + (y2-y1)^2). The length of a route is the sum of the distances when travelling from node to node along the route. If two nodes share the same location, their distance is 0. Two nodes (Roaming to Static or Static to Static) can communicate if their distance is less than or equal to the given maximum range. Round final answers to the nearest integer. If the two roaming nodes could never communicate return -1. See examples for further clarification.



Create a class Wireless that contains the method bestRoute, which takes an int range, a String[] roamNodes, and a String[] statNodes and returns an int representing the length of the shortest route between the two roaming nodes in the system at any integral time greater than or equal to 0. If the two nodes could never communicate return -1.
 

Definition

    
Class:Wireless
Method:bestRoute
Parameters:int, String[], String[]
Returns:int
Method signature:int bestRoute(int range, String[] roamNodes, String[] statNodes)
(be sure your method is public)
    
 

Notes

-Two nodes (Roaming to Static or Static to Static) can communicate if their distance if less than or equal to the given maximum range.
-Final answers must be rounded to the nearest integer (i.e. .5 and greater rounds up, below .5 rounds down)
-All routes must start at a roaming node, pass through 1 or more static nodes, and complete at a roaming node.
-UP means INCREASING Y coordinate whereas DOWN means DECREASING Y coordinate
-RIGHT measn INCREASING X coordinate whereas LEFT means DECREASING X coordinate
 

Constraints

-range will be between 1 and 30000 inclusive
-roamNodes will contain exactly 2 elements
-Each element of roamNodes will be of the form: Direction X Y where

Direction is one of UP, DOWN, LEFT, or RIGHT

X is an integer with no leading zeros between -10000 and 10000 inclusive

Y is an integer with no leading zeros between -10000 and 10000 inclusive
-statNodes will contain between 1 and 30 elements inclusive
-Each element of statNodes will be of the form: X Y where

X is an integer with no leading zeros between -10000 and 10000 inclusive

Y is an integer with no leading zeros between -10000 and 10000 inclusive
-The final answer will be within .4999 of the nearest integer.
 

Examples

0)
    
1
{"DOWN 100 200","DOWN 100 200"}
{"1000 1000"}
Returns: -1
The roaming nodes will never be close enough to the static node to communicate.
1)
    
30000
{"DOWN 10000 10000","RIGHT -10000 -10000"}
{"10000 -10000","10000 -10000"}
Returns: 0
They keep getting closer and closer until finally they all meet at the stationary node at (10000,-10000)
2)
    
3000
{"DOWN 0 10000","LEFT 10000 0"}
{"14 100","25 -10","98 204","99 1000"}
Returns: 49
3)
    
30000
{"DOWN 0 0","DOWN 0 0"}
{"10000 10000","9000 10000","8000 10000","7000 10000"}
Returns: 24413
4)
    
20
{"DOWN -20 0","DOWN 80 1"}
{"0 0","20 0","40 0","60 1"}
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

PathFinding

Graph Theory, Search



Used in:

SRM 156

Used as:

Division I Level Three

Writer:

LunaticFringe

Testers:

lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1110

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4585&pm=1110

Problem Statement

    

Given a board consisting of empty space, walls, and the starting positions of two players A and B, determine the minimum number of turns it will take for players A and B to switch positions on the board.

During a turn, one or both players may take a step. A step is defined as a unit movement up, down, left, right, or in any of the four diagonals. Players may not step into walls or off the board. Players may never share the same square at the end of a turn. Players may not cross paths during a turn. Crossing paths occurs when players A and B switch positions in a single turn. For example, assume player A is in the upper left corner of the board, and player B is in the square immediately to his right. Player A may not move right while player B moves left, since they would be passing each other. Player A can, however, move right if player B moves in any other direction.

You will be given a String[] board, representing the game board. board will contain exactly one 'A' and exactly one 'B'; each other character will be either '.' (empty space), or 'X' (a wall). Your method should return the minimum number of turns necessary for players A and B to switch positions, or -1 if this is impossible.

 

Definition

    
Class:PathFinding
Method:minTurns
Parameters:String[]
Returns:int
Method signature:int minTurns(String[] board)
(be sure your method is public)
    
 

Notes

-(In the following notes, assume that the coordinate system is given as (row, col). For example, the upper-left corner of the board is (0,0), and the square immedately below it is (1,0).)
-If player A is at (0,0) and player B is at (0,1), player A would be allowed to move down-right at the same time that player B moves down-left. This is not considered crossing paths, even though the two players would meet at (0.5, 0.5).
-However, if player A is at (0,0) and player B is at (1,1), player A would not be allowed to move down-right at the same time that player B moves up-left. This is considered crossing paths because players A and B have switched positions at the end of a single turn.
-It is permissible to move diagonally through walls. That is, a player may move from (0,0) to (1,1) even if there are walls at (0,1) and (1,0).
 

Constraints

-board will contain between 2 and 20 elements, inclusive.
-Each element of board will contain between 2 and 20 characters, inclusive.
-Each element of board will contain the same number of characters.
-Each element of board will consist of only the characters '.', 'X'. 'A', and 'B'.
-board will contain exactly one 'A' and exactly one 'B'.
 

Examples

0)
    
{"....",
 ".A..",
 "..B.",
 "...."}
Returns: 2

There are many ways to switch positions in two turns. For example, on turn one, player A could move right while player B moves up-right. Then, on turn two, player A could move down while player B stays where he is. It is illegal for the players to switch positions in a single turn. Therefore, the method returns 2.

1)
    
{"XXXXXXXXX",
 "A...X...B",
 "XXXXXXXXX"}
Returns: -1

Since the players cannot reach each other, they obviously cannot switch positions.

2)
    
{"XXXXXXXXX",
 "A.......B",
 "XXXXXXXXX"}
Returns: -1

Even though the players can reach each other, there is still no way for player B to ever get on the left side of player A.

3)
    
{"XXXXXXXXX",
 "A.......B",
 "XXXX.XXXX"}
Returns: 8

Players A and B spend the first three turns moving towards each other. On turn four, player A moves down-right while player B moves left. On turn five, player A moves up-right while player B moves left. It then takes three more turns of the players moving away from each other before they have switched positions, for a total of 8 turns.

4)
    
{"...A.XXXXX.....",
 ".....XXXXX.....",
 "...............",
 ".....XXXXX.B...",
 ".....XXXXX....."}
Returns: 13
5)
    
{"AB.................X",
 "XXXXXXXXXXXXXXXXXXX.",
 "X..................X",
 ".XXXXXXXXXXXXXXXXXXX",
 "X..................X",
 "XXXXXXXXXXXXXXXXXXX.",
 "X..................X",
 ".XXXXXXXXXXXXXXXXXXX",
 "X..................X",
 "XXXXXXXXXXXXXXXXXXX.",
 "X..................X",
 ".XXXXXXXXXXXXXXXXXXX",
 "X..................X",
 "XXXXXXXXXXXXXXXXXXX.",
 "X..................X",
 ".XXXXXXXXXXXXXXXXXXX",
 "X..................X",
 "XXXXXXXXXXXXXXXXXXX.",
 "...................X",
 ".XXXXXXXXXXXXXXXXXXX"}
Returns: 379

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Rooms

Graph Theory



Used in:

TCO '03 Qual. Round 1

Used as:

Division I Level Three

Writer:

lars2520

Testers:

brett1479 , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1095

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4700&pm=1095

Problem Statement

    You are trying to find a way around a maze which consists of a number of rooms, each of which may have doors open to other rooms that are only open at specific time periods. You will start in a certain room, at time = 0. At each time step, a set of doors will be open connecting various rooms to each other. However, the doors are all one-way, and allow passage in only one direction (though there may be two one-way doors between a pair of rooms so that you can go in either direction). Additionally, you have decided to move through a door every time step, so unless there is a door which connects a room to itself (which is possible) you must move to a new room at each time step. Only paths which move through a door at each time step are valid (see example 4).



At each time step, there will be a set of open doors which is represented by a single uppercase letter ('A'-'Z'). The maze will be represented by the input rooms, where each element of rooms tells you which doors leading out of a room are associated with which letters. Each element will be formatted as "<letter>:<adjacent room 1>,<adjacent room 2>,... <letter>:<adjacent room 1>,...". In other words, element i of rooms will be a space delimited list of the rooms that are reachable from room i via doors associated with a certain letter. Thus if
rooms = {"A:1 B:0,1","A:0"}
This means that for the letter 'A', you can get from room 1 to room 0, and from room 0 to room 1. For the letter 'B' you can get from room 0 to room 0 or from room 0 to room 1.



The second input, doors, represents which sets of doors are open at which time steps. So, if doors were "AB", then doors associated with the letter 'A' would be open at time step 0, and doors associated with 'B' would be open at time step 1. Thus, for the above example of rooms, if you started at room 1, there would be 2 possible paths with the same length as doors. You could go from room 1 to room 0 and then to room 0 again (signified "00"), or you could take the path "01".



The starting room will be denoted by the input start, which indicates that you should start in the room represented by the element start of rooms (indexed from 0). Your method should return a int[] representing which rooms can possibly be reached (at the final time step) by going through some door at each time step, and not skipping any time steps. The return should be sorted in ascending order.
 

Definition

    
Class:Rooms
Method:finalRooms
Parameters:String[], String, int
Returns:int[]
Method signature:int[] finalRooms(String[] rooms, String doors, int start)
(be sure your method is public)
    
 

Notes

-If an element of rooms does not contain some letter, this indicates that there are no doors coming out of this room associated with that letter. See example 4.
 

Constraints

-Each element of rooms will be formatted as "<letter>:<adjacent room 1>,<adjacent room 2>,... <letter>:<adjacent room 1>,...". For each <letter> present in each element, there will always be at least one adjacent room associated with it.
-No <letter> will be repeated in any element of rooms.
-Each <letter> will be an uppercase letter ('A'-'Z').
-Each <adjacent room i> will be an integer between 0 and the number of elements in rooms-1, inclusive, with no extra leading zeros. And, for each letter, no room will be repeated.
-rooms will contain between 1 and 50 elements, inclusive.
-Each element of rooms will contain between 1 and 50 characters, inclusive.
-doors will contain between 1 and 50 uppercase letters ('A'-'Z'), inclusive.
-start will be between 0 and the number of elements in rooms-1, inclusive.
 

Examples

0)
    
{"A:0 B:1","A:1 B:0"}
"AB"
0
Returns: { 1 }
We start in room 0. During the first time step, the 'A' set of doors is open, so we can go from room 0 to room 0, since the first element of rooms has "A:0". That is our only option, so we go through the door to room 0. At time step 1, the 'B' set of doors is open, and the first element of rooms tells us that we can only go from room 0 to room 1 when the 'B' set of doors is open. So, after two time steps, the only option is to be in room 1.
1)
    
{"A:1 B:0","A:0 B:1"}
"AABAAB"
1
Returns: { 1 }
2)
    
{"B:1 Z:0","B:0 Z:2","B:2 Z:1"}
"BBZZB"
0
Returns: { 1 }
3)
    
{"A:0,1,2,3","A:0,1,2,3","A:0,1,2,3","A:0,1,2,3"}
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
2
Returns: { 0,  1,  2,  3 }
Here we can get from any room to any other room when the 'A' set of doors is open.
4)
    
{"D:0","D:0","D:0","D:0"}
"GDDDDD"
3
Returns: { }

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Socialize

Graph Theory, Search



Used in:

TCI '02 Round 4

Used as:

Division I Level Two

Writer:

lars2520

Testers:

alexcchan , lbackstrom

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=1011

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4355&pm=1011

Problem Statement

    

At a recent party, a number of people were loitering around talking to one another, and generally doing partyish things. It was a very social event, and we would like to come up with some sort of a metric for how social it was. One possibility is to find the shortest distance from each person to every other person, and take the average. Your task is to write a class Socialize, with a method average, that computes the average distance between all distinct pairs of people, and returns this average, rounded to the nearest integer (.5 rounds up).

However, our metric would not be very accurate if we just took the distance between people. For example, two people could have been only a few feet from each other, but if there was a wall between them, they wouldn't have been able to socialize. Thus, we will define the distance between two people as the shortest path between them, which doesn't go through any obstacles, and where the path goes in discrete steps, with each step being one unit in any of the four cardinal directions (east, west, north and south).

Because there are various obstacles, there may be cases where two people are totally cut off from each other. In this case, you should not include the distance between them in your calculation.

For example, if the layout were ('P' represents a person, '#' represents some sort of an obstacle, and '.' represents open floor):

P...P
###..
P...#
####P

There are four people in total, one at each of the following locations (where the first coordinate is the distance along the x axis, and the second is along the y axis, with (0,0) at the upper left corner): (0,0),(4,0),(0,2),(4,3)

The person at (0,0) and the person at (4,0) are connected by a path of length 4.

The person at (0,0) and the person at (0,2) are connected by a path of length 8 because to get from one to another, they have to walk around the obstacle between them.

The person at (4,0) and the person at (0,2) are connected by a path of length 6.

The person at (4,3) can not reach any of the other people because he is blocked in (no diagonal movement), thus distances from him to other people do not play a role in the average.

Thus, there are three paths between people, whose lengths are 4,6, and 8. The average length of these paths is 6, so your method should return 6.

 

Definition

    
Class:Socialize
Method:average
Parameters:String[]
Returns:int
Method signature:int average(String[] layout)
(be sure your method is public)
    
 

Notes

-If there are no pathes between people, return 0.
 

Constraints

-layout contains between 1 and 50 elements, inclusive.
-each element of layout contains between 1 and 50 characters, inclusive.
-each element of layout will contain the same number of characters.
-each character in layout is either '#', '.', or 'P'.
 

Examples

0)
    
{"P"}
Returns: 0
1)
    
{"#"}
Returns: 0
2)
    
{"P#P"
,"P#."
,"P#P"}
Returns: 2
3)
    
{"P...P",
"###..",
"P...#",
"####P"}
Returns: 6

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Travel

Brute Force, Geometry, Graph Theory



Used in:

TCI '02 Semifinals 3

Used as:

Division I Level One

Writer:

lars2520

Testers:

alexcchan , lbackstrom

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=996

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4372&pm=996

Problem Statement

    

A traveling salesman has recently decided to go international and sell his wares around the globe. He has done in depth research and has come up with a list of cities which he thinks will provide the best market for his goods. In planning his trip, the salesman wants to minimize the total distance he has to travel because he does not particularly like traveling (which is unfortunate for him, as he is a traveling salesman) and furthermore, he figures the less distance he has to travel, the cheaper his trip will be. However, this salesman is not particularily good at math, and so you must write a computer program to help him find his way in the least distance.

You will be given a set of cities defined by their longitudes and latitudes. In addition, you will be given the radius of the planet that this traveling salesman resides on. Assume that there are direct flights, both ways, between every pair of cities that the salesman wants to visit, and that the flights follow the shortest path possible (over the surface of the planet). In addition, the first element of the input String[] will be the city in which the salesman lives, and thus his trip must start and end at this city.

Each city is defined by two numbers, a latitude and a longitude. The latitude is the number of degrees above the equator, with 90 being the north pole, and -90 being the south pole. The longitude is the number of degrees east or west of some arbitrary, predefined point. Thus, 90 degrees east is one quarter of the way around the globe in the eastern direction.

If the result is not an integer, round it to the nearest integer (.5 rounds up)

 

Definition

    
Class:Travel
Method:shortest
Parameters:String[], int
Returns:int
Method signature:int shortest(String[] cities, int radius)
(be sure your method is public)
    
 

Notes

-Assume the planet is a perfect sphere.
-To find the cartesion coordinates of a city, assuming the center of the planet is at (0,0,0), use the following formulas:

x = r*cos(latitude)*cos(longitude)

y = r*cos(latitude)*sin(longitude)

z = r*sin(latitude)
 

Constraints

-cities contains between 2 and 9 elements, inclusive.
-Each element of cities represents a unique point on the globe.
-Each element of cities is formatted as "<latitude> <longitude>" where <latitude> is an integer in the range -90 to 90, inclusive, and <longitude> is an integer in the range -180 to 180, inclusive.
-radius is an integer between 1 and 1,000, inclusive.
-to avoid rounding errors, the shortest path, prior to rounding, will not be within 0.001 of <x>+0.5 for any integer <x>.
 

Examples

0)
    
{"0 0","0 1"}
1000
Returns: 35
The two cities are located one degree apart at the same latitude
1)
    
{"0 0","0 1","0 -1","-1 0","1 0","-1 -1","1 1","1 -1","-1 1"}
1
Returns: 0
2)
    
{"40 -82","-27 -59","-40 48"
,"26 -12","-31 -37","-30 42"
,"-36 -23","-26 71","-19 83","8 63"}
698
Returns: 4505

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Doorknobs

Graph Theory, Search



Used in:

TCI '02 Round 2

Used as:

Division I Level Three

Writer:

chogyonim

Testers:

alexcchan , lbackstrom

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=979

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4335&pm=979

Problem Statement

    

Tim and Tom are playing a game called Super-Doorknobs. From a starting position inside Tim's house, they each have to try to be the first one to touch a given number of doorknobs in any order. Tom, being aware of his disadvantage of not knowing Tim's house, decides to code up a quick algorithm to tell him which doorknobs to go after.

Given the configuration of the house and the number of doorknobs they need to hit, return the length of the shortest path that includes touching the necessary number of doorknobs.

The house configuration will be a String[] birds-eye view. The game will start in the top-left corner. The following characters will represent the house:

'.' - empty square.

'o' - square with a doorknob (they touch the doorknob the moment they enter this square).

'#' - a wall that neither of them can run through.

For example, if Tim and Tom were racing to touch 3 doorknobs in the following house configuration (quotes added for clarity):

{".....",
 "o....",
 "o....",
 "o....",
 "...o."}

The shortest path is straight down, and has a total length of 3. Therefore the method would return 3.

 

Definition

    
Class:Doorknobs
Method:shortest
Parameters:String[], int
Returns:int
Method signature:int shortest(String[] house, int doorknobs)
(be sure your method is public)
    
 

Notes

-If there is no way to reach <doorknobs> doorknobs from the starting location at the top-left of the house, return -1.
-Tim and Tom can only move up, down, left, or right. Diagonals are not allowed.
 

Constraints

-house will contain between 5 and 50 elements, inclusive.
-each element of house will be of length 5 to 50, inclusive.
-each element of house will be the same length as every other element of house.
-each element of house will contain only the characters '.', '#', and/or 'o'.
-the first character of the first element of house (the top-left square) will be a '.'.
-doorknobs will be between 1 and 4, inclusive.
-the number of 'o' characters in house is between <doorknobs> and 6, inclusive.
 

Examples

0)
    
{"....."
,"o...."
,"o...."
,"o...."
,"...o."}
3
Returns: 3
1)
    
{"....."
,"o...."
,"o...."
,"o...."
,"...o."}
4
Returns: 7
2)
    
{".#..."
,"#...."
,"...oo"
,"...oo"
,"...oo"}
1
Returns: -1
Tim and Tom can't move from the starting location (what an odd house).
3)
    
{"...o."
,"o..o."
,"....."
,"..oo."
,"....."}
4
Returns: 7
4)
    
{"....#"
,".##o#"
,".##oo"
,"o##.#"
,"....#"}
4
Returns: 12
5)
    
{"....#"
,"o##o#"
,".##oo"
,".##.#"
,"....#"}
4
Returns: 8
6)
    
{".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,"...................o.............................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,"........................................o........."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,"..........o......................................."
,".................................................."
,".................................................."
,".................................................."
,".....................................o............"
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."
,".................................................."}
4
Returns: 106

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

LawnMower

Brute Force, Graph Theory



Used in:

TCO04 Round 3

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

PabloGilberto , lbackstrom , vorthys

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=926

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5880&pm=926

Problem Statement

     I am considering buying a big new riding mower, but I need to figure out how much hand trimming I will need to do. My lawn is a square n x n grid of cells. Each cell is either grass, or it is a bush. It is not possible to drive the mower over a bush.

The new mower occupies two adjacent cells. As it moves, the back end goes over the same cell that the front end previously occupied, and the front end can be steered either to the next cell in the direction the mower is headed, or to one that is 45 degrees to the left or right.The following diagrams give examples showing the possible cells (1, 2, or 3) that the front of the mower could be steered to given the location of the front(F) and back(B).

   - 1 2             - - 1
   - F 3             B F 2
   B - -             - - 3

I will build a shed for the mower which will occupy two cells that are adjacent (either diagonally or orthogonally). The shed is really just a roof over a concrete floor, so it is open on all sides and the mower can freely pass through the shed going any direction. I am willing to destroy bushes to make room for the shed. Each time I mow I must return the mower to the shed facing the same way as before I started mowing.

I don't mind going over the same places more than once, but every cell containing grass that I can't mow will have to be trimmed by hand. Create a class LawnMower that contains the method trimNeeded that takes the width of my lawn, n, and int[]s row and col giving the locations of my bushes, and returns the number of cells of grass that I will have to trim by hand (with my shed built in the best location).

An element of row and the corresponding element of col give the location of a bush. A bush may be listed more than once -- the repetitions can be ignored.

 

Definition

    
Class:LawnMower
Method:trimNeeded
Parameters:int, int[], int[]
Returns:int
Method signature:int trimNeeded(int n, int[] row, int[] col)
(be sure your method is public)
    
 

Constraints

-n is between 2 and 12 inclusive.
-row contains between 1 and 50 elements inclusive.
-col contains the same number of elements as does row.
-Each element of row is between 0 and n-1 inclusive.
-Each element of col is between 0 and n-1 inclusive.
 

Examples

0)
    
4
{0,1,0}
{0,2,0}
Returns: 6
   B S S -
   o - B o
   o - - o
   - o o -
The best place (there are other equally good places) for the shed is row 0, columns 1 and 2. The mower can just barely mow in a circle and get back to the shed. Each 'o' shows a cell that the lawn mower cuts. Note that there are only two bushes (one is repeated). Each '-' shows a grass cell that cannot be mowed.
1)
    
5
{0}
{0}
Returns: 4
With no bushes in the way (we can't get the mower into the corner anyway) and a bigger yard, we can build the shed at row 0, columns 1 and 2, and cut everything except the 4 corners and the middle. Since one of those corners has a bush, that leaves 4 grass cells that must be trimmed by hand.
2)
    
5
{3,3,3}
{4,4,4}
Returns: 5
There is just one (repeated) bush. We can build the shed on top of the bush at rows 3 and 4, column 4. We will then be able to mow everything except the four corners and the middle.
3)
    
3
{0}
{0}
Returns: 6
This yard is just too small for the mower. We can build the shed on two grass cells and just leave the mower in the shed; that leaves the 9 cells containing 1 bush, 2 shed, and 6 grass, all of which must be trimmed by hand.
4)
    
12
{11}
{11}
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Criminal

Graph Theory



Used in:

TCCC '03 Semifinals 3

Used as:

Division I Level Two

Writer:

brett1479

Testers:

Logan , lbackstrom , schveiguy

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=884

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4493&pm=884

Problem Statement

    You are working for the FBI and are trying to locate a particular criminal organization. Within the organization you know which members communicate with each other. The problem is that the members may go by aliases. Given both the information in the database about the organization, and the field data about a suspicious organization, you will determine whether they represent the same group. The two sets of data represent the same group if and only if they only differ by the names of the participants.
For example:
Database               Field Data 
FRANK ----- BOB        WILLARD ----- GEORGE
  |                       |
  |                       |
  |                       |
GEORGE                  GREG
The Database and Field Data represent the same organization even though the participants are using different names.
Renaming Scheme:
FRANK -> WILLARD           FRANK -> WILLARD         
BOB -> GEORGE       or     BOB -> GREG 
GEORGE -> GREG             GEORGE -> GEORGE
If the database data and the field data represent the same organization return how many of the members are going by aliases, otherwise return -1. If there is more than one naming scheme possible in mapping the database information to the field data, use the one that gives the greatest value for the number of aliases. So in the previous example we would use the first renaming scheme thus giving 3 instead of 2.



The database data will be given in a String[] database. Each element of database will be in the form "NAME1 NAME2" meaning that NAME1 and NAME2 communicate with each other. The field data will be given in a String[] fieldData that is formatted in the same way as database. In the above example, the input could have been formatted as:
database = {"FRANK BOB","FRANK GEORGE"}
fieldData = {"WILLARD GREG","GEORGE WILLARD"}
In any particular organization, no two people will have the same name or alias. In other words, no two different people in the database will have the same name in database. In addition, no two different people in the field data will have the same name in fieldData.
 

Definition

    
Class:Criminal
Method:numPseudonyms
Parameters:String[], String[]
Returns:int
Method signature:int numPseudonyms(String[] database, String[] fieldData)
(be sure your method is public)
    
 

Notes

-Communication is symmetric. In other words, if FRANK and BOB communicate then BOB and FRANK communicate.
 

Constraints

-database will contain between 1 and 28 elements inclusive
-fieldData will contain between 1 and 28 elements inclusive
-Each element of database will contain between 3 and 50 characters inclusive
-Each element of fieldData will contain between 3 and 50 characters inclusive
-Each element of database and fieldData will be of the form NAME1_NAME2

where '_' is a single space and NAME1 is different than NAME2

NAME1 and NAME2 will have at least 1 character, and will only contain uppercase letters ('A'-'Z')
-Each element of database and fieldData will have NO leading or trailing whitespace
-There will be between 2 and 8 unique names inclusive in database
-There will be between 2 and 8 unique names inclusive in fieldData
-database cannot contains any repeated elements. In other words, if database contains an element "A B", it cannot contain another element "A B" or "B A".
-fieldData cannot contain any repeated elements. In other words, if fieldData contains an element "A B", it cannot contain another element "A B" or "B A".
 

Examples

0)
    
{"FRANK BOB","FRANK GEORGE"}
{"WILLARD GREG","GEORGE WILLARD"}
Returns: 3
The example from above.
1)
    
{"ADAM FRANK","BOB SUZY"}
{"BRETT GEORGE","BRETT TOM"}
Returns: -1
These can't both be describing the same organization. The fieldData contains 3 distinct people where as the database contains 4.
2)
    
{"HARRY LLOYD","GEORGE BILL"}
{"FRANK THOMAS","GEORGE WILL","WILL FRANK"}
Returns: -1
These can't both be describing the same organization. The number of pairs of communicating members differs.
3)
    
{"A B","A C","AA BB","AA CC","AA DD"}
{"A B","A C","AA BB","AA CC","AA DD"}
Returns: 5
4)
    
{"A B"}
{"A B"}
Returns: 2
5)
    
{"STEVE BRETT", "STEVE LARS", "STEVE JAMES"}
{"SCHVEIGUY ADMINBRETT", "ADMINBRETT LBACKSTROM", "LBACKSTROM STEVEVAI"}
Returns: -1

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WordTrain

Graph Theory, Sorting, String Manipulation



Used in:

SRM 247

Used as:

Division I Level Two

Writer:

dgoodman

Testers:

PabloGilberto , lbackstrom , brett1479

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=875

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=7222&pm=875

Problem Statement

    

We have a collection of train cars. We want to hook them together to get the train with the most cars possible. Some cars have a unique front end, and some can have either end in front. Two cars can be coupled together only if their coupling mechanisms are compatible.

Each car is described by a String of uppercase letters. The front end is the end with the letter that comes first in the alphabet (if it starts and ends with the same letter, either end can be in front). Two words can be hooked together only if the two adjoining ends have the same letter. Create a class WordTrain that contains the method hookUp that takes cars, a String[], and returns a String which is the longest word train that can be made from cars.

If more than one train of the longest length is possible, return the one that comes first alphabetically. Remember that the length of a train is the number of cars, not the number of letters.

The returned string should be all the cars in the train, starting at the front of the train, concatenated with '-' showing the coupling between adjacent cars. For alphabetic breaking of ties, the '-' is included in its usual order in the ASCII sequence.

 

Definition

    
Class:WordTrain
Method:hookUp
Parameters:String[]
Returns:String
Method signature:String hookUp(String[] cars)
(be sure your method is public)
    
 

Constraints

-cars contains between 1 and 50 elements inclusive.
-Each element of cars contains only uppercase letters ('A'-'Z').
-Each element of cars contains between 3 and 10 characters inclusive.
 

Examples

0)
    
{"CBA","DAA","CXX"}
Returns: "ABC-CXX"
This is the only possible train of length 2. Note that CBA needed to be reversed so that it was facing the right direction.
1)
    
{"ACBA"}
Returns: "ABCA"
2)
    
{"AUTOMATA","COMPUTER","ROBOT"}
Returns: "COMPUTER-ROBOT"
3)
    
{"AAA","AAAA","AAA","AAA"}
Returns: "AAA-AAA-AAA-AAAA"
'-' sorts before uppercase letters
4)
    
{"ABA","BBB","COP","COD","BAD"}
Returns: "BBB-BAD"

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Robbery

Graph Theory, Simulation



Used in:

TCO04 Semifinal 1

Used as:

Division I Level Three

Writer:

dgoodman

Testers:

PabloGilberto , lbackstrom , Yarin

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=838

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=5882&pm=838

Problem Statement

    A city is square and is laid out in nice regular blocks, except that there is one block that has a "shortcut", a narrow road that goes diagonally through the block. The bank has just been robbed, and our one on-duty police car starts to chase down the robbers. The police and robbers always drive at top speed, and they have exactly the same top speed. Neither the police nor the robbers can leave the city.

It takes 10 seconds to drive one block. It also takes 10 seconds to drive the shortcut. The police have one advantage -- they have a "bug" in the robbers' car. One of the robbers tells the driver which way to turn just before they reach each intersection, so the police can choose their next turn appropriately. The robbers are apprehended when the police and robbers are at the same intersection at the same time or when a head-on collision occurs on the shortcut. (The regular roads are divided roads, so the police cannot apprehend the robbers if they pass each other going in opposite directions.) U-turns at intersections are possible, but neither the police nor the robbers may slow down or stop.

Create a class Robbery that contains the method apprehend that takes the width of the city, n, and a int[] map, giving the locations of the shortcut, robbers and police as inputs and returns the amount of time until the robbers are apprehended. If the police can never apprehend the robbers, the method should return -1. Assume that both the police and robbers behave optimally (other than robbing the bank in the first place).

n is the number of blocks in both directions (since the city is square). The intersections are located at x,y where x and y are between 0 and n inclusive. map contains exactly 8 values: shortcutX1,shortcutY1,shortcutX2,shortcutY2, policeX,policeY,robbersX,robbersY.

 

Definition

    
Class:Robbery
Method:apprehend
Parameters:int, int[]
Returns:int
Method signature:int apprehend(int n, int[] map)
(be sure your method is public)
    
 

Constraints

-n is between 2 and 30 inclusive.
-map contains exactly 8 elements.
-Each element in map is between 0 and n inclusive.
-The absolute value of (shortcutX1 - shortcutX2) is 1.
-The absolute value of (shortcutY1 - shortcutY2) is 1.
-map specifies distinct locations for the police and robbers.
 

Examples

0)
    
3
{0,1,1,2,1,1,3,1}
Returns: 30
*---*---*---*
|   |   |   |
*---*---*---*
| / |   |   |
*---P---*---R
|   |   |   |
*---*---*---*

(All example diagrams have (0,0) in the lower left corner.)
If the robbers go west, the police will go east apprehending in 1*10 seconds. If the robbers go south, the police will go east. Then the robbers will have to go north or west and will be apprehended after 2*10 = 20 seconds. If the robbers go north, they will be trapped when they get to the northeast corner of the city, and will be apprehended after 30 seconds.
1)
    
3
{0,1,1,2,1,1,2,1}
Returns: 50
*---*---*---*
|   |   |   |
*---*---*---*
| / |   |   |
*---P---R---*
|   |   |   |
*---*---*---*
The best strategy for the police is to go west, then northeast (using the shortcut). The robbers can do no better than to head north, then east, then south and south. Even so, they will then be trapped in the southeast corner of the city and will be apprehended 10 seconds later.
2)
    
3
{1,2,2,1,2,2,1,2}
Returns: 50
*---*---*---*
|   |   |   |
*---R---P---*
|   | \ |   |
*---*---*---*
|   |   |   |
*---*---*---*
3)
    
3
{1,0,0,1,3,0,1,0}
Returns: 70
*---*---*---*
|   |   |   |
*---*---*---*
|   |   |   |
*---*---*---*
| \ |   |   |
*---R---*---P
4)
    
5
{1,3,2,2,1,2,0,2}
Returns: 60
*---*---*---*---*---*
|   |   |   |   |   |
*---*---*---*---*---*
|   |   |   |   |   |
*---*---*---*---*---*
|   | \ |   |   |   |
R---P---*---*---*---*
|   |   |   |   |   |
*---*---*---*---*---*
|   |   |   |   |   |
*---*---*---*---*---*
5)
    
5
{2,3,1,4,0,5,0,4}
Returns: 90
P---*---*---*---*---*
|   |   |   |   |   |
R---*---*---*---*---*
|   | \ |   |   |   |
*---*---*---*---*---*
|   |   |   |   |   |
*---*---*---*---*---*
|   |   |   |   |   |
*---*---*---*---*---*
|   |   |   |   |   |
*---*---*---*---*---*

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

RiverHill

Graph Theory, Search



Used in:

TCI '02 Round 3

Used as:

Division I Level Three

Writer:

chogyonim

Testers:

alexcchan , lbackstrom

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=759

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4345&pm=759

Problem Statement

    

A river can flow either downhill, or at a level elevation for a certain distance. Given a topographical map (a map representing elevations) and a maximum level flow distance, write a method to determine the largest area that a river can cover, if it starts at any location on the map.

The map will be a String[] representing the elevations of each coordinate, with each elevation being a single digit number between 0 (lowest) and 9 (highest).

The maximum level flow distance, maxDist, will be the longest a river can travel on level ground. So if the distance is 0, a river must flow downhill. If the distance is 1, it can flow to 1 adjacent coordinate of the same altitude, in each direction, before it must flow downhill. If the distance is 2, immediately after flowing downhill (or from the starting point), the river can flow to any adjacent coordinate of the same altitude, and then once again to any coordinate adjacent to the new one and of the same altitude, before it must go down hill. For this calculation, the river flows in the 4 primary directions (north, south, east, and west). Notice that since a river will go in any direction it can, it's more of a "flood" than a "river". Thus when determining the area covered by a river starting at a certain point, you must find the area of all the points that can be reached following the above constraints.

For example:
0000000000
0111111110
0122222210
0123333210
0123443210
0123443210
0123333210
0122222210
0111111110
0000000000

Represents a peak with an elevation of 4.

If maxDist = 2 and the river starts flowing at the '*' then the river can cover an area of 16, shown by '~'.

~~~~~~~000
~~*~~11110
~~22222210
~123333210
~123443210
0123443210
0123333210
0122222210
0111111110
0000000000
However this isn't the largest area. If the river starts flowing at the peak, then the river can cover the entire area of 100.
 

Definition

    
Class:RiverHill
Method:largest
Parameters:String[], int
Returns:int
Method signature:int largest(String[] map, int maxDist)
(be sure your method is public)
    
 

Notes

-The river can only flow north, south, east, and west in determining the maximum level flow distance.
-Each coordinate has an area of 1.
 

Constraints

-map will contain between 2 and 40 elements, inclusive.
-each element of map will contain between 2 and 40 characters, inclusive.
-each element of map will contain the same number of characters as every other element of map.
-each element of map will contain only the characters '0'-'9' inclusive. There will be no spaces.
-maxDist will be an integer between 0 and 10, inclusive.
 

Examples

0)
    
{"0000000000"
,"0111111110"
,"0122222210"
,"0123333210"
,"0123443210"
,"0123443210"
,"0123333210"
,"0122222210"
,"0111111110"
,"0000000000"}
2
Returns: 100
By starting the river at the peak (in either position), the river will be able to flow over the whole mountain.
1)
    
{"0000000000"
,"0111111110"
,"0122222210"
,"0123333210"
,"0123443210"
,"0123443210"
,"0123333210"
,"0122222210"
,"0111111110"
,"0000000000"}
1
Returns: 95
If you started at the northwest corner of the peak, the only spaces not reachable would be the 5 spaces diagonally southeast from the start.
2)
    
{"0000000000"
,"0111111110"
,"0122222210"
,"0123333210"
,"0123443210"
,"0123443210"
,"0123333210"
,"0122222210"
,"0111111110"
,"0000000000"}
0
Returns: 9
By starting the river at the peak (at any of the four elevation 4 positions), the river will only be able to flow downward in the 4 main directions, thus it will be two straight streams, with an area of 9.
3)
    
{"555505555"
,"555515555"
,"555525555"
,"555535555"
,"555545555"
,"555545555"
,"555555555"}
1
Returns: 11
5555~5555
5555~5555
5555~5555
5555~5555
55~5~5555
5~*~~5555
55~555555
One of the best rivers starts at the asterix (*).
4)
    
{"5565236785012472"
,"3469912625904101"
,"5943545942017700"
,"9109166568720711"
,"6136079994373860"
,"4129136148916755"
,"2975832922074121"
,"4674050103662805"
,"2494729679116165"
,"1611964958059846"
,"2384128690120444"
,"1010697089697114"
,"0089682613597732"
,"4971774663111966"
,"8543141293776080"
,"4298494798935152"
,"5202757354375791"
,"5376161470010537"
,"5696381123743171"
,"1446566116127226"}
2
Returns: 32
One of the best rivers (possibly uniquely the best) starts at the space on the 4th row, 6th column (both 0-indexed). The method returns 32.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Resort

Graph Theory, String Manipulation



Used in:

TCI '02 Round 3

Used as:

Division I Level Two

Writer:

chogyonim

Testers:

alexcchan , lbackstrom

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=590

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4345&pm=590

Problem Statement

    

At most ski resorts, the runs (a run is defined as an inclined course on which one can ski downhill) are rated by their difficulty. The three classifications commonly used are Green Circle for easy, Blue Square for medium, and Black Diamond for hard. However, there can be a situation where a run is rated easy, but only feeds into hard runs (meaning that all paths from the easy run to the bottom pass through hard runs). Thus, even though the run itself is easy, it should be classified as Black Diamond, since the easiest path to the base of the mountain involves a hard run. Note that one run may feed into many other runs, and that since you are skiing downhill, once you feed into another run, there will be no way to return to any previously skied run (in other words the transitive closure of feeds is acyclic).

For the purposes of this problem, the terms "easy", "medium", and "hard" shall refer to the actual difficulty of the given run, and "Green Circle", "Blue Square", and "Black Diamond" shall refer to the compound difficulty of the easiest path to the base of the mountain from that run (called the "classification").

Given the run configuration for a ski resort, return the classification of the requested run.

The run configuration will be in the form of a String[], with each element formatted as (quotes added for clarity):

"<name>:<difficulty>,<feed1>,<feed2>,<feed3>,..."

Where <name> is the run's unique name, <difficulty> is a single character representing the difficulty ('E'asy, 'M'edium, or 'H'ard). The <feedX> arguments are all of the runs that <name> feeds into. There can be between 0 and 5 feeds, inclusive. So for example:

"BLACK STALLION:M,BLUE MOUNTAIN,FLYING TOPCODER,DOKS RUN"

is a medium run named BLACK STALLION, which feeds into BLUE MOUNTAIN, FLYING TOPCODER, and DOKS RUN. If all 3 of these were hard, then BLACK STALLION would have to be classified "BLACK DIAMOND", even though it by itself would have been a "BLUE SQUARE".

For the requested run, return either "BLACK DIAMOND" if the easiest path to the base of the mountain must include a hard run, "BLUE SQUARE" if the easiest path to the base of the mountain must include a medium run, but no hard run, and "GREEN CIRCLE" if the easiest path to the base of the mountain is all easy runs.

If, and only if, a run feeds into no other runs, it ends at the base of the mountain and should be treated as the easiest route from itself to the base. Thus if it is rated 'M', it is classified "BLUE SQUARE".

 

Definition

    
Class:Resort
Method:classify
Parameters:String[], String
Returns:String
Method signature:String classify(String[] runs, String classify)
(be sure your method is public)
    
 

Notes

-The classification of a run is not affected by the difficulty of any runs which feed into it.
 

Constraints

-runs will contain between 1 and 50 elements, inclusive
-each element of runs will consist of only capital letters ('A'-'Z'), spaces, commas (','), and a colon (':').
-each element of runs will contain between 3 and 50 characters, inclusive, and will be formatted as (quotes added for clarity): "<name>:<difficulty>,<feed1>,<feed2>,<feed3>..."
-there may be between 0 and 5 feeds, inclusive, for each run.
-there will be no commas except for a single comma between feeds and between the difficulty and the first feed (if there is a first feed).
-<difficulty> will be a single character capital letter, either 'E', 'M', or 'H'.
-<name> will be between 1 and 48 characters in length, inclusive.
-<name> will be unique and consist of only capital letters ('A'-'Z') and spaces, but will not begin or end with a space.
-each feed will reference a run that appears as <name> in some element of runs (this is necessary to determine its difficulty).
-within each element of runs, the feeds will be unique.
-runs will contain no loops, i.e. runs will contain no circular or self references.
-classify will be between 1 and 48 characters in length, inclusive, and will reference a run that appears as <name> in some element of runs.
 

Examples

0)
    
{"BLACK STALLION:M,BLUE MOUNTAIN,TOPCODER,DOKS RUN"
,"BLUE MOUNTAIN:H"
,"TOPCODER:H"
,"DOKS RUN:H,CHOGYS RUN"
,"CHOGYS RUN:M,EASY RUN,MEDIUM RUN,HARD RUN"
,"EASY RUN:E"
,"MEDIUM RUN:M"
,"HARD RUN:H"}
"BLACK STALLION"
Returns: "BLACK DIAMOND"
The path to the base must go through either BLUE MOUNTAIN, TOPCODER, or DOKS RUN, all of which are hards.
1)
    
{"BLACK STALLION:M,BLUE MOUNTAIN,TOPCODER,DOKS RUN"
,"BLUE MOUNTAIN:H"
,"TOPCODER:H"
,"DOKS RUN:H,CHOGYS RUN"
,"CHOGYS RUN:M,EASY RUN,MEDIUM RUN,HARD RUN"
,"EASY RUN:E"
,"MEDIUM RUN:M"
,"HARD RUN:H"}
"DOKS RUN"
Returns: "BLACK DIAMOND"
Since DOKS RUN itself is hard, it doesn't matter how hard the runs below it are.
2)
    
{"BLACK STALLION:M,BLUE MOUNTAIN,TOPCODER,DOKS RUN"
,"BLUE MOUNTAIN:H"
,"TOPCODER:H"
,"DOKS RUN:H,CHOGYS RUN"
,"CHOGYS RUN:M,EASY RUN,MEDIUM RUN,HARD RUN"
,"EASY RUN:E"
,"MEDIUM RUN:M"
,"HARD RUN:H"}
"CHOGYS RUN"
Returns: "BLUE SQUARE"
CHOGYS RUN is a medium difficulty. Since the easiest path from CHOGYS RUN to the base of the mountain is CHOGYS RUN->EASY RUN, and a medium difficulty is the hardest run in the path, CHOGYS RUN is classified as "BLUE SQUARE".
3)
    
{"NOOB CITY:E,GREEN BARON,RISKY RUN,LEAP OF FAITH"
,"GREEN BARON:E"
,"RISKY RUN:M"
,"LEAP OF FAITH:H"}
"NOOB CITY"
Returns: "GREEN CIRCLE"
The easiest path is NOOB CITY->GREEN BARON, both of which are easy.
4)
    
{"NOOB CITY:E,RISKY RUN,LEAP OF FAITH"
,"RISKY RUN:M"
,"LEAP OF FAITH:H"}
"NOOB CITY"
Returns: "BLUE SQUARE"
The easiest path is NOOB CITY->RISKY RUN, and RISKY RUN is a medium difficulty.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

TopPilot

Graph Theory



Used in:

TCI '02 Semifinals 4

Used as:

Division I Level Two

Writer:

chogyonim

Testers:

alexcchan , lbackstrom

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=577

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4373&pm=577

Problem Statement

    

TopPilot airlines is committed to customer service and convenience. Thus, it is not simply enough to have a flight from San Francisco, CA to Hartford, CT. There must be a direct flight.

You will be given a String[] representing one-way flight paths. For each element in the String[], the element index is the departure airport number (0-indexed, so the first element is airport 0) and the element is a comma-delimited list of airport numbers to which there is a direct flight from the departure airport.

Write a method that, given these one-way flight paths, adds direct one-way flights between airports that are currently connected by non-direct one-way flights. For example, if there is a direct flight from SFO to JFK and a direct flight from JFK to LAX, and not a direct flight from SFO to LAX, then add a direct flight from SFO to LAX. Do not, however, add a direct flight from an airport to itself, even if a loop exists. Once this is done, the method should return the total number of flights provided by TopPilot airlines.

 

Definition

    
Class:TopPilot
Method:addFlights
Parameters:String[]
Returns:int
Method signature:int addFlights(String[] destinations)
(be sure your method is public)
    
 

Notes

-If the destination airport does not appear as an element in destinations (which is always the case when it is greater than 19), there are no departing flights from that airport.
-Leading zeroes in the numbers are allowed.
 

Constraints

-No airport will have a direct flight to itself.
-destinations will have between 1 and 20 elements, inclusive.
-each element of destinations will contain only the characters '0' through '9', and commas ','.
-each element of destinations will be a comma delimited list of integers, with no numbers repeated, and no leading, trailing, or extra commas.
-each element of destinations will be contain between 1 and 50 characters, inclusive.
-destination airport numbers will be between 0 and 50, inclusive.
 

Examples

0)
    
{"1","2","3"}
Returns: 6
There is a flight from airport 0 to airport 1, from 1 to 2, and from 2 to 3. We add a direct flight from 0 to 2, from 1 to 3, and from 0 to 3 (note that 3 is not an element, so it has no departing flights).
1)
    
{"1","02","3","4,5"}
Returns: 14
We add flights from 0 to 2, 3, 4, and 5. We add flights from 1 to 3, 4, and 5. We add flights from 2 to 4 and 5. Together with the 5 flights we already have, there are 14 total.
2)
    
{"1,2","0,2","1"}
Returns: 6
The only added flight is from 2 to 0.
3)
    
{"1,5,7,8,13,15,16,23,26,35,32,41"
,"0,2,5,6,7,15,18,21,25,31,34,41,49,50"
,"5,10,15,20,25,30,35,40,45,50"}
Returns: 62

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Solver

Dynamic Programming, Graph Theory



Used in:

TCCC '02 NE/SE Reg. Quart.

Used as:

Division I Level Three

Writer:

chogyonim

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=389

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=60&pm=389

Problem Statement

    
PROBLEM STATEMENT
After writing a careful and correct data checking method, a problem writer then
has to code a solution.  This is what you should now do.

Implement a class Solver with a method largest() that will take a String[]
lovers as an argument.  Each element of lovers will be formatted as follows:
"NAME1 LOVES NAME2" (quotes added for clarity).
With the capital word LOVES in between names, and the names containing only
capital letters [A-Z] and/or hyphens '-'.

For each NAME2 in lovers there will be a corresponding NAME1.  One person may
love multiple people (repeated NAME1), multiple people may love one person
(repeated NAME2), but no person may love themselves (NAME1 equals NAME2).

Return the number of people involved in the largest love triangle.  That is,
the largest chain of people such that:
A LOVES B
B LOVES C
C LOVES D
D LOVES E
E LOVES A
until the last person loved (NAME2--in this example A) appears somewhere else
in the chain as NAME1, at which point the triangle starts and ends with that
name.
The triangle above consists of 5 people (A B C D and E).

A love triangle can consist of 2 or more people.

DEFINITION
Class name: Solver
Method name: largest
Parameters: String[]
Returns: int
The method signature is:
int largest(String[] lovers)
Be sure your method is public.

TopCoder will ensure the following (there is no difference between these and
the 500 point problem psuedo-restrictions):
*lovers will contain between 2 and 20 elements, inclusive.
*Each element of lovers will contain less than or equal to 40 characters and
will be formatted as
 "NAME1 LOVES NAME2" (quotes added for clarity again)
 with the capital word LOVES and only one space between words.
*NAME1 and NAME2 will be names of non-zero length.
*NAME1 and NAME2 will not be identical (everyone loves themselves anyway).
*NAME1 and NAME2 will contain only capital letters [A-Z] and/or hyphens '-'.
*For each NAME2 there will be a corresponding NAME1 in lovers.  That is,
everyone loves someone else in the problem.
*One person may love multiple people (repeated NAME1 in different elements) and
one person may be loved by multiple people (repeated NAME2 in different
elements).

*It is possible for two elements to be identical.
 (ex {"A LOVES B","A LOVES B","B LOVES A"} is valid).

EXAMPLES
{"D LOVES M",
 "M LOVES D",
 "T LOVES G",
 "G LOVES D"}
The largest love triangle (between D and M) is 2.

{"ME LOVES YOU",
 "ME LOVES YOU",
 "YOU LOVES ME"}
The largest triangle is between YOU and ME, so the method returns 2.

{"A LOVES B",
 "B LOVES C",
 "C LOVES A",
 "B LOVES D",
 "D LOVES E",
 "E LOVES C",
 "E LOVES F",
 "F LOVES G",
 "G LOVES F"}
This looks as follows:

/---<---\
|       |
A->-B->-C
    |   ^
    v   |
    D->-E
        |
        v
    G<->F

A->B->D->E->C->A is the largest triangle, which is of size 5.

{"A LOVES B",
 "B LOVES C",
 "C LOVES B",
 "B LOVES A"}

Either A->B->A or B->C->B are legal, and both of size 2.  We see that
A->B->C->B->A is not legal since, by the above definition of triangle, once
person B appears as both NAME2 and NAME1 in the triangle, the triangle can go
no further and must start and end with person B (giving B->C->B).  The method
should return 2.
 

Definition

    
Class:Solver
Method:largest
Parameters:String[]
Returns:int
Method signature:int largest(String[] param0)
(be sure your method is public)
    

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

BinBlocks



Used in:

SRM 39

Used as:

Division I Level Three , Division II Level Three

Writer:

kyky

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=223

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4010&pm=223

Problem Statement

    
PROBLEM STATEMENT

Using blocks of binary logic defined by their truth tables, build a block with
a desired truth table. Each block of binary logic has two inputs and two
outputs. Block inputs are referred to as i0 and i1; block outputs are referred
to as o0 and o1. Logic inside a block implements its truth tables for each of
its two outputs. To build a block with the target truth table, connect blocks
in a chain, wiring both outputs of a block to both inputs of another block.
Your method should return the number of blocks in the shortest chain
implementing the target truth table, or -1 when it is impossible to build a
chain with the target truth table.

DEFINITION
Class name: BinBlocks
Method name: targetChain
Parameters: String[], String
Return type: int

Method signature: int targetChain(String[] blocks, String target) (make sure
your method is public)

Both the target and the elements of blocks are String representations of truth
tables formatted as follows (quotation marks are used for clarity - they are
not part of the strings):
"abcd,efgh"
Each character represents a digit '0' or '1'. Group abcd represents the truth
table of the output o0, while efgh represents the truth table of the output o1.
The characters of "abcd,efgh" correspond to the following states of inputs:

i0 i1  |  o0 o1
-------+-------
0  0   |  a  e
1  0   |  b  f
0  1   |  c  g
1  1   |  d  h

For example, truth table "0001" corresponds to the truth table of the operation
AND: (i0 AND i1).

TopCoder will check that
- blocks will contain 0 to 50 elements, inclusive, and
- all truth tables are properly formatted

NOTES
* Blocks are ordered. Your method may not alter the order of the blocks while
building the target chain. It may, however, skip any number of blocks.
* For certain values of target, the optimal chain would consist of zero logical
blocks. See examples 1 and 2.
* When connecting logical blocks A and B in a chain, you may wire outputs to
inputs in either of the two ways: A o0 to B i1 and A o1 to B i1, or A o0 to B
i1 and A o1 to B i0. This rule applies even in cases when the optimal chain is
empty.

EXAMPLES
1. blocks= {}, target="0101,0011". targetChain should return 0 because wiring
i0 to o0 and i1 to o1 implements the target truth table.
2. blocks= {"0000,1111","0000,0101"}, target="0011,0101". targetChain should
return 0 because wiring i0 to o1 and i1 to o0 implements the target truth
table, without using any of the blocks.
3. blocks= {"0001,0111","1010,1100"}, target="1110,1000". targetChain should
return 2 because you need to wire both blocks in a sequence to get the target
truth table.
4. blocks= {"0001,0111","0101,0011"}, target="0111,0001". targetChain should
return 1 because the target truth table is the "flipped" truth table of the
block 0.
5. blocks= {}, target="1111,0000". targetChain should return -1 because it is
impossible to implement the target truth table.
6. blocks= {"0101,1010","0110,1001","1110,0001","1010,1100","1000,0001"},
target= "1111,0000". targetChain should return 2. For a graphical
representation of this please refer to
http://www.topcoder.com/contest/blocks.html
7 a. blocks={"0001,1101","1010,1011"}, target="0010,0011". targetChain returns 2
  b. blocks={"0001,1101","1010,1011"}, target="0011,0010". targetChain returns 2
  c. blocks={"0001,1101","1010,1011"}, target="1110,1111". targetChain returns 2
  d. blocks={"0001,1101","1010,1011"}, target="1111,1110". targetChain returns 2
  e. blocks={"0001,1101","1010,1011"}, target="0100,0101". targetChain returns 2
  f. blocks={"0001,1101","1010,1011"}, target="0101,0100". targetChain returns 2

 

Definition

    
Class:BinBlocks
Method:targetChain
Parameters:String[], String
Returns:int
Method signature:int targetChain(String[] param0, String param1)
(be sure your method is public)
    

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Networking

Dynamic Programming, Graph Theory, Math



Used in:

TCI '01 Finals

Used as:

Division I Level Three

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=209

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=57&pm=209

Problem Statement

    
THIS PROBLEM WAS TAKEN FROM THE FINALS OF THE TOPCODER INVITATIONAL TOURNAMENT

PROBLEM STATEMENT
A network consists of a system of numNodes nodes, numbered from 0 to
numNodes-1, and connections between those nodes.  A connection has a chance of
being up and a chance of being down. Implement a class Networking that contains
a method getProbability which calculates the chance that there will be a path
from node 0 to node numNodes-1 such that each connection in the path is up.
(See the examples to see how probabilities can be calculated)

DEFINITION
Class Name: Networking
Method Name: getProbability
Parameters: int, String[]
Returns: double
Method signature (be sure your method is public):  double getProbability(int
numNodes, String[] connections);

numNodes is an int representing the number of nodes.
connections is a String[] representing the connections.  The elements will be
of the form "N1 N2 P" where N1 and N2 represent the numbers of the two nodes
the connection connects, and P is the probability the connection will be up.
There will be precisely one space between N1 and N2 and one space between N2
and P.  The nodes are numbered from 0 to numNodes-1. Every connection connects
two nodes (or possibly a node to itself).

OUTPUT
A double representing the probability there exists a path from node 0 to node
numNode-1 such that every connection in the path is up. Your result must be
within 10^-6 of our solution's result (tolerance for double inaccuracies).

NOTES
* A "path" is a series of one or more connections such that each successive
connection starts at the node where the previous connection ended.
* The connections are bi-directional.
* There can be multiple (parallel) connections connecting two nodes.

TopCoder will ensure the validity of the inputs.  Inputs are valid if all of
the following criteria are met:
* numNodes is an integer between 2 and 10, inclusive.
* Elements of connections are of the form described in the input above.
* connections has between 0 and 20 elements, inclusive.
* P is a decimal value between 0 and 1 inclusive with exactly one digit before
the decimal point and two digits after the decimal point.
* N1 and N2 are single integer digits between 0 and numNodes-1, inclusive.

EXAMPLES
* Nodes are in series. For example, if numNodes = 3 and connections = {"0 1
0.20", "1 2 0.10"}, the network looks as follows (letters are added for
clarity):
 ___             ___              ___
|   |   0.20    |   |    0.10    |   |   
| 0 |-----------| 1 |------------| 2 |
|___|     a     |___|      b     |___|

In this case, the probability of a connection from 0 to 2 is the probability
that a AND b are up. The AND relationship corresponds to multiplication.
Therefore, to calculate this all you need to do is mutliply the probability of
0->1 by the probability of 1->2. 
                (0.20 * 0.10) = 0.02
So the method should return 0.02.


* Nodes are in parallel. If numNodes = 4 and connections = {"0 1 0.10", "1 3
0.20", "0 2 0.30", "2 3 0.40"}, the network looks as follows:
                 ___
                |   |
     0.10 /-----| 1 |-----\  0.20
         /      |___|      \
 ___    / a               b \  ___
|   |  /                     \|   |
| 0 | /                       | 3 |
|___| \                      /|___|
       \         ___        /
        \ c     |   |    d /
         \------| 2 |-----/
       0.30     |___|       0.40

In order for this to happen, either a and b have to be up, or c and d have to
be up. The probability a connection exists from 0 to 3 now becomes the
probability that (a AND b are up) OR (c AND d are up). 

This equals P(a AND b up) OR P(c AND d up) = P(a up)*P(b up) + P(c up)*P(d up)
- P(a and b and c and d up) = 0.1 * 0.2 + 0.3 * 0.4 - 0.1 * 0.2 * 0.3 * 0.4 =
0.1376.

(The probability that they are all up is subtracted out at the end because it
is added as both P(a AND b up) and P(c AND d up)).

* If numNodes=2 and connections = {"0 1 0.80"}, there is a path from node 0 to
node 1 when the connection is up, so the method should return 0.8.


* If numNodes=3 and connections = {"0 2 0.50", "0 2 0.50", "0 1 0.10", "1 2
0.20","1 1 0.60"}, there is a path from node 0 from node 2 if either of the
first two connections are up or if both the 3rd and 4th connection are up, so
the method should return 0.755.  Note the connection from node 1 to node 1 does
not affect the result.


* If numNodes=4 and connections = {"0 2 0.06", "3 1 1.00", "1 3 0.50", "1 2
0.00"}, the method should return 0.0.


* If numNodes=4 and connections = {"0 1 0.10", "1 3 0.20", "0 2 0.30", "2 3
0.40", "1 2 0.60"}, the method should return 0.17048.
This can be calculated by reducing the network as follows:

The original network looks like:
                ___
          _____|   |_____     
    0.10 /     | 1 |     \  0.20
        /      |___|      \
 ___   / a       |       b \  ___
|   | /          |e         \|   |
| 0 |/           |0.60       | 3 |
|___|\           |          /|___|
      \         _|_        /
       \ c     |   |    d /
        \______| 2 |_____/
      0.30     |___|       0.40

This solution can be found by reducing the network.  
The chance the network is up is P(e up)*P(Network up, given e up) + P(e
down)*P(Network up, given e down).

P(Network up, given e up):

Given e up, the network becomes:

         0.10           0.20
       ______         ________
 ___  /  a   \  ___  /    b   \  ___
|   |/        \|   |/          \|   |
| 0 |\   c    /|1,2|\     d    /| 3 |
|___| \______/ |___| \________/ |___|
         0.30           0.40

The probability this is up is :

P((a OR c up) AND (b OR d up)) =
P(a OR c up) * P(b OR d up) =
(0.1+ 0.3- 0.1 * 0.3) * (0.2 + 0.4-0.2 * 0.4) = 0.1924

Given e down, the network becomes:
                 ___
                |   |
     0.10 /-----| 1 |-----\  0.20
         /      |___|      \
 ___    / a               b \  ___
|   |  /                     \|   |
| 0 | /                       | 3 |
|___| \                      /|___|
       \         ___        /
        \ c     |   |    d /
         \------| 2 |-----/
       0.30     |___|       0.40

And low and behold, this is the network from the last example, and the
probability of it being up is: 0.1376

Therefore, the probability of the entire network being up is:
P(e up)*P(Network up, given e up) + P(e down)*P(Network up, given e down) =
0.6 * 0.1924 + 0.4 * 0.1376 = 0.17048
The method should return 0.17048.
 

Definition

    
Class:Networking
Method:getProbability
Parameters:int, String[]
Returns:double
Method signature:double getProbability(int param0, String[] param1)
(be sure your method is public)
    

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

FSM

Graph Theory, String Manipulation



Used in:

TCI '01 Round 2

Used as:

Division I Level Three

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=179

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=51&pm=179

Problem Statement

    
Class Name: FSM
Method Name: runFSM
Paramaters: String String String[]
Returns String[]

Implement a class FSM, which contains a method runFSM.  The method runs an
augmented finite state machine:

The augmented finite state machine consists of a number of states.  Each state
has a unique name of type String.  There are edges connecting the states.
These edges are directional: they go in only one direction, their source state
to their sink state (source and sink states are described below).  Each edge
has a corresponding symbol and function that are both represented as Strings.

Here is the method signature (be sure your method is public):
String[] runFSM(String symbols, String states, String[] edges)

Input:
*symbols - The first parameter to runFSM is a String containing elements
referred to as symbols that will be passed to the FSM.  The elements/symbols
will contain letters only (A-Z and a-z, inclusive).  Each element of the
symbols input parameter is separated by one or more spaces.

*states - The second parameter to runFSM is a String containing elements that
refer to the names of the states.  The names/states will contain letters (A-Z
and a-z, inclusive) only.  The first state in this list is the starting state.
Each element of the states input parameter is separated by one or more spaces.

*edges[] - The third parameter is a String[].  Each element in the String[]
describes an edge.  The Strings in the array will contain four sets of letters,
where the sets are separated by one or more spaces.  Parsing the String from
the left-most character moving right, the first set of letters is the source
state - the state in which the edge starts.  The second set of letters is the
sink state - the state in which the edge ends.  The third set of letters is the
symbol corresponding to the edge.  The fourth set of letters is the function
corresponding with the edge.

Output:
The output is a String[] containing a list of all the functions called with
their associated symbols as parameters, in order.  There should be only one
element in the output for each symbol in the first input String.

The augmented finite state machine is passed a sequence of symbols.  Each
symbol is processed as follows:
1.  Use the first state (the first element of the states String) as the source
state and let that equal the current state.
2.  Determine the first symbol (i.e. the first element of the symbols String)
let that equal the current symbol.
3.  Find the edge of the current state that corresponds to the current symbol.
4.  Add a String to the output array.  The String should consist of the
function name of the edge found in step 3 with the current symbol enclosed in
parentheses (i.e. if the function is "open" and the symbol is "hi", the
function call is "open(hi)").
5.  Move to the sink state that corresponds with the current symbol.
6.  Let current state be equal to the sink state from step 5
7.  Repeat steps 3 - 6 for the remaining symbols.

Note:
* If ever there is no edge leaving the current state with the current symbol,
add the String "ERROR" to the output array, remain at the current state, and go
on to the next symbol.
* No two edges may contain the same source state and symbol.
* All String comparisons are case sensitive.
* The output is a list of the function calls created in step four (above) in
order.
* The sink state can be equal to the source state
* There may be additional spaces at the beginning or end of any input String.

TopCoder will ensure:
- All the Strings and elements of arrays will contain letters (A-Z and a-z,
inclusive) and spaces (' ') only.
- The states mentioned in the edges array will be present in the states String.
- symbols will contain at least one element.
- states will contain at least one element.
- symbols and states will have length between 1 and 50, inclusive.
- edges will contain between 1 and 50 elements, inclusive, and each element
will contain between 1 and 50 characters, inclusive.
- No two edges will have the same source state and symbol
- Elements of the edges array will be well formed.  That is, each element will
be in the form: "(source state) (sink) (state symbol) (function)" (the
parentheses are for clarity and should not be included in the String).  There
will be exactly four elements separated by one or more spaces


Examples:
Example relating to a vending machine that releases candy every time 20 cents
is put in, assume:
states="Zerocents Fivecents Tencents Fifteencents Twentycents"
and
edges={
"Zerocents  Fivecents  nickel needMoreOne",
"Zerocents  Tencents dime   needMoreTwo",
"Fivecents  Fifteencents dime   needMoreThree",
"Fivecents  Tencents nickel needMoreFour",
"Tencents Fifteencents nickel needMoreFive",
"Tencents Twentycents dime   releasingCandyOne",
"Fifteencents Twentycents nickel releasingCandyTwo",
"Fifteencents Twentycents dime   releasingCandyThree",
"Twentycents Fivecents  nickel needMoreSix",
"Twentycents Tencents dime   needMoreSeven"
}

If symbols="nickel dime dime", the output should be:
{"needMoreOne(nickel)",
 "needMoreThree(dime)",
 "releasingCandyThree(dime)"}

If symbols="dime oops dime" the output should be
{"needMoreTwo(dime)",
 "ERROR",
 "releasingCandyOne(dime)"}

If symbols="dime nickel dime dime dime nickel" the output should be
{"needMoreTwo(dime)",
 "needMoreFive(nickel)",
 "releasingCandyThree(dime)",
 "needMoreSeven(dime)",
 "releasingCandyOne(dime),
 "needMoreSix(nickel)}

More Examples:
If symbols=" a   a  a b  b   c" and
states=" stateZero stateOne stateTwo"
and edges=
{"stateZero stateOne a doSomething",
 "stateOne stateTwo b doNothing",
 "stateTwo stateZero c doEverything"}

The output should be
{"doSomething(a)",
 "ERROR",
 "ERROR",
 "doNothing(b)",
 "ERROR",
 "doEverything(c)"}
 

Definition

    
Class:FSM
Method:runFSM
Parameters:String, String, String[]
Returns:String[]
Method signature:String[] runFSM(String param0, String param1, String[] param2)
(be sure your method is public)
    

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

WhaleWatcher



Used in:

SRM 33

Used as:

Division I Level Two , Division II Level Two

Writer:

jay_peg

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=175

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4003&pm=175

Problem Statement

    
Class name: WhaleWatcher
Method name: getWhaleSightings
Parameters: String[], int,  int , int , String 
Returns: int

Implement a class WhaleWatcher, which has a method getWhaleSightings.

TopCoder will enforce the following rules:
*WhalePositions has between 1 and 10 Strings, inclusive.
*Passengers is between 1 and 100, inclusive.
*StartPosition is between 0 and 9, inclusive
*TripDistance is between 0 and 9, inclusive.
*Weather is one of "Cloudy", "Foggy", "Sunny"
*The elements of WhalePositions are of the form "X,Y", where X and Y represent
integers between 0 and 9, inclusive.
*The elements of WhalePositions will be distinct (not repeated)

(In this problem statement, the variable names will sometimes be enclosed in
angle brackets <> for clarity)

The following are true:
*All action takes place on a 10x10 grid whose cells are referenced by Strings
of the form "X,Y" where X and Y are between 0 and 9.
*The point "0,0" through "9,0" are the cells in the water next to the shoreline.
*The good ship Orca takes on up to 100 passengers and leaves port at a point
represented by "StartPosition,0".
*It then travels straight out to sea until it reaches the position
"StartPosition,TripDistance".  That is, the ship starts at the point
"StartPosition,0", moves to "StartPosition,1", etc. until it reaches the point
"StartPosition,TripDistance".
Another way to say this is "The boat starts at <StartPosition> and moves up
<TripDistance> number of grid spaces".  If you think of the boat moving through
time, then at time 1, the boat would be at "StartPositionX,0".  At time 2, the
boat would be at "StartPosition,1", and at time <TripDistance>, the boat would
be at "StartPosition,TripDistance".

Your method should return the total number of times a passenger sees a whale on
this trip.

*The passenger's position on the boat does not matter.
The passengers will see whales in the following way:
*The passengers never see whales that are directly under the boat.
*If the weather is "Foggy", passengers will only see whales that are in the
cells immediately adjacent to the boat. (If boat is at "2,3", passengers will
see whales that are in the cells "1,4", "2,4", "3,4", "1,3", "3,3", "1,2",
"2,2" and "3,2")
*If the weather is "Cloudy", passengers will see whales up to 2 cells away from
the boat.
*If the weather is "Sunny", passengers will see whales up to 3 cells away from
the boat.

*The boat will move on the aforementioned path one graph unit at a time.
Each time the boat moves, check to see which whales can be seen.
*If a whale is seen by the passengers once, never count that whale again.

The method signature is (be sure your method is public):
public int getWhaleSightings(String[] WhalePositions, int Passengers, int
StartPosition, int TripDistance, String Weather)

Example 1:

WhalePositions = { "2,3", "5,6" }
passengers = 50
StartPosition = 5
TripDistance = 4
Weather = "Sunny"

The boat starts at "5,0" and will move through the cells "5,1", "5,2", "5,3",
and "5,4".


Grid: 

  0 1 2 3 4 5 6 7 8 9
 +-+-+-+-+-+-+-+-+-+-+
9| | | | | | | | | | |
 +-+-+-+-+-+-+-+-+-+-+
8| | | | | | | | | | |
 +-+-+-+-+-+-+-+-+-+-+
7| | | | | | | | | | |
 +-+-+-+-+-+-+-+-+-+-+
6| | | | | |W| | | | |
 +-+-+-+-+-+-+-+-+-+-+
5| | | | | | | | | | |
 +-+-+-+-+-+-+-+-+-+-+
4| | | | | |5| | | | |
 +-+-+-+-+-+-+-+-+-+-+
3| | |W| | |4| | | | |
 +-+-+-+-+-+-+-+-+-+-+
2| | | | | |3| | | | |
 +-+-+-+-+-+-+-+-+-+-+
1| | | | | |2| | | | |
 +-+-+-+-+-+-+-+-+-+-+
0| | | | | |1| | | | |
 +-+-+-+-+-+-+-+-+-+-+
  0 1 2 3 4 5 6 7 8 9

Legend: 
W = whale
A number N = the position the boat is in at time N


When the boat is at:            Passengers See Whales at:
---------------------------------------------------------
"5,0"                           "2,3"
"5,1"                           "2,3" (2nd sighting)
"5,2"                           "2,3" (3rd sighting)
"5,3"                           "2,3" (4th sighting), "5,6"
"5,4"                           "2,3" (5th sighting), "5,6" (2nd sighting)

The passengers saw a total of 2 whales so return 50 * 2 = 100.


Example 1:

WhalePositions = { "2,3", "5,6", "9,0", "9,1", "8,2"}
passengers = 12
StartPosition = 9
TripDistance = 1
Weather = "Foggy"

The boat starts at "9,0" and will move to the cell "9,1".


Grid:

  0 1 2 3 4 5 6 7 8 9
 +-+-+-+-+-+-+-+-+-+--+
9| | | | | | | | | |  |
 +-+-+-+-+-+-+-+-+-+--+
8| | | | | | | | | |  |
 +-+-+-+-+-+-+-+-+-+--+
7| | | | | | | | | |  |
 +-+-+-+-+-+-+-+-+-+--+
6| | | | | |W| | | |  |
 +-+-+-+-+-+-+-+-+-+--+
5| | | | | | | | | |  |
 +-+-+-+-+-+-+-+-+-+--+
4| | | | | | | | | |  |
 +-+-+-+-+-+-+-+-+-+--+
3| | |W| | | | | | |  |
 +-+-+-+-+-+-+-+-+-+--+
2| | | | | | | | |W|  |
 +-+-+-+-+-+-+-+-+-+--+
1| | | | | | | | | |2W|
 +-+-+-+-+-+-+-+-+-+--+
0| | | | | | | | | |1W|
 +-+-+-+-+-+-+-+-+-+--+
  0 1 2 3 4 5 6 7 8 9

Legend: 
W = whale
A number N = the position the boat is in at time N

(The ninth column is widened to accomodate the two chars that show
that the boat and a whale are in the same cell at that time)


When the boat is at:            Passengers See Whales at:
---------------------------------------------------------
"9,0"                           "9,1"
"9,1"                           "9,0", "8,2"

The passengers saw a total of 3 whales so return 12 * 3 = 36.


Test cases:

WhalePositions = "0,9"
passengers = 14
StartPosition = 0
TripDistance = 9
Weather = "Foggy"
returns 14

WhalePositions = "8,1" "8,2" "9,9"
passengers = 10
StartPosition = 9
TripDistance = 4
Weather = "Cloudy"
returns 20

WhalePositions = "5,5" "4,3" "6,1" "5,9"
passengers = 5
StartPosition = 5
TripDistance = 5
Weather = "Sunny"
returns 15

 

Definition

    
Class:WhaleWatcher
Method:getWhaleSightings
Parameters:String[], int, int, int, String
Returns:int
Method signature:int getWhaleSightings(String[] param0, int param1, int param2, int param3, String param4)
(be sure your method is public)
    

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Prerequisites

Graph Theory, String Parsing



Used in:

TCI '01 Round 1

Used as:

Division I Level Three , Division II Level Three

Writer:

lars2520

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=164

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=50&pm=164

Problem Statement

    
***Note:  Please keep programs under 7000 characters in length.  Thank you


Class Name: Prerequisites
Mathod Name: orderClasses
Parameters: String[]
Returns: String[]

You are a student at a college with the most unbelievably complex prerequisite
structure ever. To help you schedule your classes, you decided to put together
a program that returns the order in which the classes should be taken.  

Implement a class Prerequisites which contains a method orderClasses.  The
method takes a String[] that contains the classes you must take and returns a
String[] of classes in the order the classes should be taken so that all
prerequisites are met.

String[] elements will be of the form (and TopCoder will ensure this):
"CLASS: PRE1 PRE2 ..." where PRE1 and PRE2 are prerequisites of CLASS.  CLASS,
PRE1, PRE2, ... consist of a department name (3 or 4 capital letters, A-Z
inclusive) followed by a class number (an integer between 100 and 999,
inclusive).  The department name should be immediately followed by the class
number with no additional characters, numbers or spaces (i.e. MATH217).  It is
not necessary for a class to have prerequisites.  In such a case, the colon is
the last character in the String.  

You can only take one class at a time, therefore, use the following rules to
determine which class to take :
1) Any prerequisite class(es) listed for a class must be taken before the class
can be taken.
2) If multiple classes can be taken at the same time, you take the one with the
lowest number first, regardless of department.
3) If multiple classes with the same number can be taken at the same time, you
take the department name which comes first in alphabetical order.  
4) If the inputted course schedule has errors, return a String[] of length 0.
There is an error if it is impossible to return the classes in an order such
that all prerequisites are met, or if a prerequisite is a course that does not
have its own entry in the inputted String[].

Examples of valid input Strings are:
"CSE111: CSE110 MATH101"
"CSE110:"

Examples of invalid input Strings are:
"CS117:" (department name must consist of 3 - 4 capital letters, inclusive)
"cs117:" (department name must consist of 3 - 4 capital letters, inclusive)
"CS9E11:" (department name must be letters only)
"CSE110: " (no trailing spaces allowed)
"CSE110: CSE101 " (no trailing spaces allowed)
"MATH211: MAM2222" (class number to large)
"MATH211: MAM22" (class number to small)
"ENGIN517: MATH211" (department name to large)

Here is the method signature (be sure your method is public):
String[] orderClasses(String[] classSchedule);

TopCoder will make sure classSchedule contains between 1 and 20 Strings,
inclusive, all of the form above.  The Strings will have between 1 and 50
characters, inclusive.  TopCoder will check that the syntax of the Strings are
correct: The Strings will contain a valid class name, followed by a colon,
possibly followed by a series of unique prerequisite classes separated by
single spaces.  Also, TopCoder will ensure that each class has at most one
entry in the String[]. 

Examples:
If classSchedule={
"CSE121: CSE110",
"CSE110:",
"MATH122:",
}
The method should return: {"CSE110","CSE121","MATH122"}

If classSchedule={
"ENGL111: ENGL110",
"ENGL110: ENGL111"
}
The method should return: {}

If classSchedule=[
"ENGL111: ENGL110"
}
The method should return: {}

If classSchedule={
"CSE258: CSE244 CSE243 INTR100"
"CSE221: CSE254 INTR100"
"CSE254: CSE111 MATH210 INTR100"
"CSE244: CSE243 MATH210 INTR100"
"MATH210: INTR100"
"CSE101: INTR100"
"CSE111: INTR100"
"ECE201: CSE111 INTR100"
"ECE111: INTR100"
"CSE243: CSE254"
"INTR100:"
}
The method should return:
{"INTR100","CSE101","CSE111","ECE111","ECE201","MATH210","CSE254","CSE221","CSE2
43","CSE244","CSE258"}
 

Definition

    
Class:Prerequisites
Method:orderClasses
Parameters:String[]
Returns:String[]
Method signature:String[] orderClasses(String[] param0)
(be sure your method is public)
    

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Inheritance



Used in:

SRM 14

Used as:

Division I Level Two , Division II Level Two

Writer:

Logan

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=104

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=3013&pm=104

Problem Statement

    
Class name: Inheritance
Method name: resolve
Parameters: String[], String, String
Returns: String

As Java programmers, you are familiar with the mechanics of inheritance.  Each
class (except for Object) has an ancestor (in Java this ancestor is specified
after the "extends" keyword; when no ancestor is specified, the class extends
Object).  Each class inherits certain methods of its parent class, as well as
those of its parent, and so on, all the way back to Object.  However, a class
can also define its own version of each of these methods, overriding the one
inherited from its ancestors.

When a method is called on a particular object, there must be a mechanism at
work to determine which class's method is used.  For instance, if the toString
method is called on an object of a class that does not implement its own
toString method, then that class's parent is checked to see if it implements
that particular method.  If it doesn't, then its parent is checked in the same
manner, all the way up to Object, which has no parent.  If even Object does not
implement the method, then that method is not defined for the object it was
called on.

Implement a class Inheritance, which contains a method resolve.  The method
takes a description of all the available classes as a String[], a class name as
a String, and a method name called on the class as a String, and returns a
String that is the name of the class that defines the method that should be
executed.

The method signature is:
public String resolve(String[] classes, String className, String methodName);

The String[] contains the descriptions of each of the available classes.  Each
element of this String[], describe a single class.  The description of a class
is in the form of "CLASSNAME|PARENTNAME|METHOD1,METHOD2...".  If the class does
not have a parent (like Object in Java), then PARENTNAME will be of zero
length.  The description of the methods is a comma-separated list of method
names.  Each method is separated only by a comma (no whitespace).

Given className and methodName, the method returns the name of the class that
defines the method which should be called according to the rules outlined
above.  If the method specified by methodName does not exist in the given class
nor any of its ancestors, your method should return the empty string ("").

Constraints:
- The name of the parent class in each class's description must be the name of
some other class
- There cannot be cycles in the inheritance graph (in other words, no class can
be allowed to inherit from any class of which it is an ancestor)
- The names of all classes and methods may only contain letters, digits, and
the underscore character ('_'), and must begin with a letter or underscore
- The name of any class or method may be no less than one character and no more
than 50 characters in length
- There may be at most 50 classes
- Each class may define at most 10 methods
- All method names in the method list for each class must be unique
- The class name passed as the second parameter of your method must be the name
of some class defined in the classes String[]

The tester will ensure that all of the above constraints are met before any
input is passed to your method.

Notes:
- Because of the constraints listed above, there must be at least one class
defined with no ancestor (there may be more than one)
- All string comparisons are case sensitive

Examples:

Given the class description:
["A||a,b,c",
 "B|A|b,c,d",
 "C||e,f",
 "D|C|"
 "E|D|f,g"
 "F|B|b,h,i"]

-If className="A" and methodName="b" the method returns "A".
-If className="F" and methodName="c" the method returns "B".
-If className="E" and methodName="a" the method returns "".
-If className="D" and methodName="e" the method returns "C".
-If className="F" and methodName="a" the method returns "A".

Given the class description:

["Object||toString,getClass"
 "String|Object|toString"
 "InputStream|Object|read,close,reset"
 "FileInputStream|InputStream|read,close"]

-If className is "String" and methodName is "toString", the method returns
"String".
-If className is "String" and methodName is "getClass", the method returns
"Object".
 

Definition

    
Class:Inheritance
Method:resolve
Parameters:String[], String, String
Returns:String
Method signature:String resolve(String[] param0, String param1, String param2)
(be sure your method is public)
    

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Connected

Graph Theory



Used in:

TCCC '01 Semifinals 3

Used as:

Division I Level Three

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=69

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=2007&pm=69

Problem Statement

    
 

Definition

    
Class:
    

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

Nails

Dynamic Programming, Graph Theory



Used in:

TCCC '01 Semifinals 1

Used as:

Division I Level Three

Writer:

Unknown

Testers:



Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=66

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=2005&pm=66

Problem Statement

    
 

Definition

    
Class:
    

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816
Nikolay.IT 2009-2012