Becoming a Good Problems Solver ― Challenging ICPC-2003/2004 Yaw-Ling Lin Dept Computer Science & Info. Management, Providence University, Taichung, Taiwan. 1 27th Annual ACM ICPC World Finals • • • • • • • 68 final teams 3,850 teams 1,329 universities 68 countries 106 sites Champions: Warsaw University. The 27th Annual ACM International Collegiate Programming Contest, March 25, 2003, in Beverly Hills, California. 2 ICPC2002 Kaohsiung: 8 Problems 3 ICPC Kaohsuing, Nov 09, 2002 Rank Team 1 Zhongshan University=>Bearcat (6) 2 National University of Singapore=>NUS-SOC (6) 3 National Chiao-Tung University=>NCTU Fresh Team (6) 4 Chiao Tung University=>Invulnerable Champion (6) 5 The Chinese University of Hong Kong=>CUHK Libra (5) 6 National Tsing Hua University=>Eagle (5) 7 National Taiwan University=>Pheonix (5) 8 The University of Hong Kong=>HKU CE (5) 9 National Taiwan University=>Yatta (5) 10 National Taiwan University=>Joking Kids (5) 4 ICPC2003 World: 10 Problems • • • • • A: Building Bridges B: Light Bulbs C: Riding the Bus D: Eurodiffusion E: Covering Whole Holes • • • • • F: Combining Images G: A Linking Loader H: A Spy in the Metro I: The Solar System J: Toll 5 ICPC 2003 Results ICPC2003 (前55名) 9 15 13 13 13 7 9 10 6 5 5 1 5 1 0 9 8 8 7 6 5 4 3 4 3 6 2003 ACM-ICPC World Finals Rank Name Solved 1 Warsaw University (1) – Poland 9 2 Moscow State University (1) – Russia 8 3 St Petersburg Institute (5) – Russia 7 4 Comenius University – Slovakia 7 5 Tsinghua University – China 7 6 Shanghai JiaoTong University – China 7 7 Saratov State University – Russia 7 8 Zhongshan University (13) – China 6 13 California Inst Tech, UC Berkeley – USA 6 13 Fudan; Zhejiang University – China 6 13 U Tokyo, U Singapore – Japan, Singapore 6 21 Carnegie Mellon University (9) 5 30 Harvard (13) 4 43 National Chiao-Tung University (13) 3 7 ICPC Problem Sets • ICPC2003-World – http://icpc.baylor.edu/icpc/Finals/Problems.html • ICPC2002-Kaohsiung – http://icpc.baylor.edu/past/icpc2003/Regionals/Rep orts/icpc.baylor.edu/icpc/regionals/Kaohsiun02/ind ex.html 8 Various Kinds of Problems • • • • • • Algorithms Simulation System Programming Geometry Combinatorics Modeling, Situation Analysis 9 G. Polya, "How to Solve It“, 1957 1. Understanding The Problem 2. Devising A Plan 3. Carrying Out The Plan 4. Looking Back - If you can't solve a problem, then there is an easier problem you can solve: find it. 10 UNDERSTANDING THE PROBLEM • First. You have to understand the problem. • What is the unknown? What are the data? What is the condition? • Is it possible to satisfy the condition? Is the condition sufficient to determine the unknown? Or is it insufficient? Or redundant? Or contradictory? • Draw a figure. Introduce suitable notation. • Separate the various parts of the condition. Can you write them down? 11 DEVISING A PLAN • Second. Find the connection between the data and the unknown. Consider auxiliary problems if an immediate connection cannot be found. • Have you seen it before? • Do you know a related problem? • Look at the unknown! Think of a familiar problem having the same or a similar unknown. • Could you restate the problem? Could you restate it differently? Go back to definitions. • If you cannot solve the proposed problem try to solve first some related problem. • Did you use all the data? Did you use the whole condition? 12 CARRYING OUT THE PLAN • Third. Carry out your plan. • Carrying out your plan of the solution, check each step. Can you see clearly that the step is correct? Can you prove that it is correct? 13 LOOKING BACK • Fourth. Examine the solution obtained. • Can you check the result? Can you check the argument? • Can you derive the solution differently? Can you see it at a glance? • Can you use the result, or the method, for some other problem? 14 Look at the Problems -- Problems Types • • • • • • • Algorithms Dynamic Programming Simulation System Programming Geometry Combinatorics Problem Solving 15 Basic Techniques • English / Problem Modeling • Combinatorics / Discrete Math – Counting – Recurrence – Graphs, Trees, Connectivity • Algorithm: – Dynamic Programming – Graph Searching: DFS/BFS, Shortest Path, MST, Tree Traversal • Efficient (Human) Programming 16 Training • • • • • • • • • Solve as many past ICPC problems as possible. English reading and Problem Modeling read Polya. Thoroughly understand discrete math / structure Understand / practice algorithmic techniques: read algorithm + data structure text book Optional: Computational Geometry, String algorithms Programming efficiency: routine gadgets, fast-typing, debugging tricks, writes, writes. writes … Communications / discussions between members. Leadership / role-playing / execution. Time devotion. 17 Members • • • • English / Problem Understanding Problem Modeler / Dispatcher Human-Time Efficient Programmers Team Work 18 ICPC2003 World: 10 Problems • • • • • A: Building Bridges B: Light Bulbs C: Riding the Bus D: Eurodiffusion E: Covering Whole Holes • • • • • F: Combining Images G: A Linking Loader H: A Spy in the Metro I: The Solar System J: Toll 19 A: Building Bridges City 1 City 3 No bridges are needed City 1 with bridges City 2 No bridges are possible City 4 City 4 with bridges 20 A: Building Bridges • Bridges may be built only on the grid lines that form the edges of the squares. Each bridge must be built in a straight line and must connect exactly two buildings. • For a given set of buildings, you must find the minimum number of bridges needed to connect all the buildings. If this is impossible, find a solution that minimizes the number of disconnected groups of buildings. • Among possible solutions with the same number of bridges, choose the one that minimizes the sum of the lengths of the bridges, measured in multiples of the grid size. Two bridges may cross, but in this case they are considered to be on separate levels and do not provide a connection from one bridge to the other. 21 A: Building Bridges 22 Building Bridges: Solutions City 1 City 3 No bridges are needed City 1 with bridges City 2 No bridges are possible City 4 City 4 with bridges • Block: Nodes • Connectivity: Weighted Edges • Model: Minimum Spanning Tree 23 B: Light Bulbs first switch first bulb second switch third switch second bulb third bulb nth switch (n-1)st bulb nth bulb 24 B: Light Bulbs • Each remaining switch (1 < i < n) toggles the states of the three bulbs with indices i – 1, i, and i + 1. • The minimum cost of changing a row of bulbs from an initial configuration to a final configuration is the minimum number of switches that must be flipped to achieve the change. • 01100 represents a row of five bulbs in which the second and third bulbs are both ON. You could transform this state into 10000 by flipping switches 1, 4, and 5, but it would be less costly to simply flip switch 2. • Decimal integers are used instead of binary for the bulb configurations. Thus, 01100 and 10000 are represented by the decimal integers 12 and 16. 25 B: Light Bulbs 26 Light Bulbs: Solution • 10100 01110 == 00000 11010 • x1 xor x2 = b1 • x1 xor x2 xor x3 = b2 x3 = b1 xor b2 • i.e. x3 = 0 AND x3 = 0 1 • How about 111000 110011 001011 ? – ??00?? ?100?? 110001 • In general, we shall have: – ??b??b??b?...?b exact – ??b??b??b?...?b? exact – ??b??b??b?...?b?? two cases … 27 C: Riding the Bus 28 C: Riding the Bus • The order-3 curve contains 9 smaller copies of the order-2 curve (with 4 reversed left to right), connected by line segments, as described for the order-2 curve. Higher order curves are drawn in a similar manner. • The connecting points to which processor components attach are evenly spaced every len units along the bus. The first connecting point is at (0,0) and the last is at (1,1). There are 9k connecting points along the order-k curve, and the total bus length is (9k–1) len units. • You must write a program to determine the total distance that signals must travel between two processor components. Each component’s coordinates are given as an x, y pair, 0 x 1 and 0 y 1, where x is the distance from the left side of the chip, and y is the distance from the lower edge of the chip. 29 C: Riding the Bus 30 Riding the Bus: Solution • • • • • Recursive Structure, recursive formula Locating the smallest cell containing the points Find the nearest edge Find the distances within cells Find the distances between cells 31 D: Eurodiffusion 32 D: Eurodiffusion • Member states decorate the coins with their own motif. No matter which motif is on the coin, it can be used anywhere in the 12 Member States. • You must write a program to simulate the dissemination of euro coins throughout Europe. Each city belongs to a country, and a country is a rectangular part of the plane. Initially, each city has one million (1000000) coins in its country’s motif. Every day a representative portion of coins, based on the city’s beginning day balance, is transported to each neighbor of the city. A representative portion is defined as one coin for every full 1000 coins of a motif. • A city is complete when at least one coin of each motif is present in that city. A country is complete when all of its cities are complete. Your program must determine the time required for each country to become complete. 33 D: Eurodiffusion 34 Eurodiffusion: Solution • Simulation • Graph Model: Vertex Connectivity • Iterative Flowing and Testing 35 E: Covering Whole Holes • Whether a given cover can be used to completely cover a specified hole. Covers and holes are rectangular polygons • Moreover, both cover and hole are aligned along the same coordinate axes, and are not supposed to be rotated against each other — just translated relative to each other. 36 E: Covering Whole Holes Input: the input consists of several descriptions of covers and holes. The first line of each description contains two integers h and c (4 h 50 and 4 c 50), the number of points of the polygon describing the hole and the cover respectively. Each of the following h lines contains two integers x and y, which are the vertices of the hole’s polygon in the order they would be visited in a trip around the polygon. The next c lines give a corresponding description of the cover. Both polygons are rectangular, and the sides of the polygons are aligned with the coordinate axes. The polygons have positive area and do not intersect themselves. The last description is followed by a line containing two zeros. Output: For each problem description, print its number in the sequence of descriptions. If the hole can be completely covered by moving the cover (without rotating it), print “Yes” otherwise print “No”. Recall that the cover may extend beyond the boundaries of the hole as long as no part of the hole is uncovered. Follow the output format in the example given below. 37 E: Covering Whole Holes 38 Covering Whole Holes: Solution • Computational Geometry • PLAN: very few numbers of edges • Aligning the top edge and the left edge (double pairing) • Testing overlaps 39 F: Combining Images 40 F: Combining Images • The Quad Tree encoding of an image is a string of binary digits. For easier printing, a Quad Tree encoding can be converted to a Hex Quad Tree encoding by the following steps: • Prepend a 1 digit as a delimiter on the left of the Quad Tree encoding. • Prepend 0 digits on the left as necessary until the number of digits is a multiple of four. • Convert each sequence of four binary digits into a hexadecimal digit, using the digits 0 to 9 and capital A through F to represent binary patterns from 0000 to 1111. 41 F: Combining Images • If an image is homogeneous (all its pixels are of the same color), the Quad Tree encoding of the image is 1 followed by the color of the pixels. For example, the Quad Tree encoding of an image that contains pixels of color 1 only is 11, regardless of the size of the image. • If an image is heterogeneous (it contains pixels of both colors), the Quad Tree encoding of the image is 0 followed by the Quad Tree encodings of its upperleft quadrant, its upper-right quadrant, its lower-left quadrant, and its lower-right quadrant, in order. 42 Combining Images: Solution • • • • • Recurrence: The Quad Tree encoding. PLAN: expand the formula to an n by n square array. ANDing the two array Converting the square array to a Quad Tree formula. Encoding? – 0abcd – 1x • Str2Tree ? Level? Tree2Mat(T, lev)? Mat2Tree, Tree2Str 43 G: A Linking Loader • An object module contains (in order) zero or more external symbol definitions, zero or more external symbol references, zero or more bytes of code and data (that may include references to the values of external symbols), and an end of module marker. In this problem, an object module is represented as a sequence of text lines, each beginning with a single uppercase character that characterizes the remainder of the line. 44 G: A Linking Loader • • • • “D symbol offset” is an external symbol definition. Starting at the address 10016, the line “D START 5C” indicates that the symbol START is defined as being associated with the address 15C16. The number of D lines in a test case is at most 100. “E symbol” is an external symbol reference, The line “E START” indicates that the value of the symbol START. Each of the “E” lines for each module is numbered sequentially, starting with 0, so they can be referenced in the “C” lines. “C n byte1 byte2 … byten” specifies the first or next n bytes of code and data for the current module. The value n is specified as a one or two digit hexadecimal number, and will be no larger than 10 hexadecimal. Each byte is either a one or two digit hexadecimal number, or a dollar sign. The values specified for the other bytes (those not following a dollar sign) are loaded into sequential memory locations, starting with the first (lowest) unused memory location. For example, the line “C 4 25 $ 0 37” would cause the values 2516 0116 5C16 and 3716 to be placed in the next four unused memory locations, assuming the first “E” line for the current module specified a symbol defined as having the address 15C16. If the 0-origin index of the external symbol reference is an undefined symbol, the 16-bit value inserted at the current point in the linked program is 000016. A line of the form “Z” marks the end of an object module. 45 G: A Linking Loader 46 Linking Loader: Solution • System Programming – Tips: Read the problem carefully – Know the meaning of every symbol – How these values are packed / related to each other • Symbol Table / Translation • String Matching algorithm 47 H: A Spy in the Metro 48 H: A Spy in the Metro • Maria knows that a powerful organization is after her. She also knows that while waiting at a station, she is at great risk of being caught. To hide in a running train is much safer, so she decides to stay in running trains as much as possible, even if this means traveling backward and forward. Maria needs to know a schedule with minimal waiting time at the stations that gets her to the last station in time for her appointment. 49 H: A Spy in the Metro • • • • • • • • • Input The input file contains several test cases. Each test case consists of seven lines with information as follows. The integer N (2 N 50), which is the number of stations. The integer T (0 T 200), which is the time of the appointment. N-1 integers: t1, t2, ... tN-1 (1 ti 20), representing the travel times for the trains between two consecutive stations: t1 represents the travel time between the first two stations, t2 the time between the second and the third station, and so on. The integer M1 (1 M1 50), representing the number of trains departing from the first station. M1 integers: d1, d2, ... dM1 (0 di 250 and di < di+1), representing the times at which trains depart from the first station. The integer M2 (1 M2 50), representing the number of trains departing from the Nth station. M2 integers: e1, e2, ... eM2 (0 ei 250 and ei < ei+1) representing the times at which trains depart from the Nth station. 50 H: A Spy in the Metro 51 Spy in Metro: Solution • Simulation / Dynamic Programming … • (time, delay) calculations ; stop at the deadline (34, 3) 0 (0, 0) 10 25 30 40 (15, 0) (5, 0) 5 5 15 30 35 45 (36, 1) 10 15 25 40 45 55 (29, 0) (23, 0) 8 11 26 36 56 5 20 30 50 6 52 I: The Solar System 53 I: The Solar System The orbits obey three laws discovered by Johannes Kepler. These laws, also called “The Laws of Planetary Motion,” are the following. 1. The orbits of the planets are ellipses, with the sun at one focus of the ellipse. (Recall that the two foci of an ellipse are such that the sum of the distances to them is the same for all points on the ellipse.) 2. The line joining a planet to the sun sweeps over equal areas during equal time intervals as the planet travels around the ellipse. 3. The ratio of the squares of the revolutionary periods of two planets is equal to the ratio of the cubes of their semi major axes. 54 I: The Solar System • In this problem, you are to compute the location of a planet using Kepler’s laws. You are given the description of one planet in the Solar System (i.e., the length of its semi-major axis, semi-minor axis, and its revolution time) and the description of a second planet (its semi-major axis and semiminor axis). • Assume that the second planet’s orbit is aligned with the coordinate axes (as in the above figure), that it moves in counter clockwise direction, and that the sun is located at the focal point with non-negative x-coordinate. • You are to compute the position of the second planet a specified amount of time after it starts at the point with maximal x-coordinate on its orbit (point B in the above figure). 55 I: The Solar System • Input • The input file contains several descriptions of pairs of planets. Each line contains six integers a1, b1, t1, a2, b2, t. The first five integers are positive, and describe two planets as follows: • a1 = semi major axis of the first planet’s orbit • b1 = semi minor axis of the first planet’s orbit • t1 = period of revolution of the first planet (in days) • a2 = semi major axis of the second planet’s orbit • b2 = semi minor axis of the second planet’s orbit • The non-negative integer t is the time (in days) at which you have to determine the position of the second planet, assuming that the planet starts in position (a2,0). • The last description is followed by a line containing six zeros. 56 Solar System: Solution • Compute the period. t2 = t1 * sqrt(a23/a13) • The planet starts in position (a2,0); sun at (c, 0), c2+b2 = a2,why? • Converting the time t = t mod t2 • A(x): The (upper half) ellipses area, covered by the left focus; – Numerical Integration – Polar System: dA = r dθ/ 2 • Find the x such that A(x) = A(a2) * t / t2 – Parametric (Binary) Searching 57 J: Toll 58 J: Toll • Each town and village demanded an entry toll. The toll for entering a village was simply one item. The toll for entering a town was one piece per 20 items carried. For example, to enter a town carrying 70 items, you had to pay 4 items as toll. • Finding the cheapest route is a real challenge. The best route depends upon the number of items carried. For numbers up to 20, villages and towns charge the same. For large numbers of items, it makes sense to avoid towns and travel through more villages. 59 J: Toll 60 Toll: Solution • Graph Searching + Dynamic Programming • Backward Searching ; Cheapest Route? 76 72 71 70 66 42 11 12 10 45 39 44 13 12 11 43 42 61 ICPC2002 Kaohsiung: 8 Problems 62 E: Trees Isomorphism 63 Trees Isomorphism: Solution • Find the root; Figure out the structure. • Tree to Standard Form (String) of the Shape: • Prefix Coding: – T1 7 3 2 1 1 2 1 1 2 1 1 ; – T2 7 2 2 1 1 4 2 1 2 1 1; – T3 7 3 2 1 1 2 1 1 2 1 1 ; 64 F: Tree Size 65 F: Tree Size i k j • Consider nodes i, j, k – Path length p(i, *) = (M[i][k]+M[i][j]-M[j][k])/2; • Find the min p(i, *) by trying all possible j, k pair • Shrink i • Repeat the process until there is only one edge. 66 Final Remarks • • Be brave, my friend, be brave. Keep cool, How to solve it? 1. 2. 3. 4. • • Understanding The Problem Devising A Plan Carrying Out The Plan Looking Back You can do it! Downdload: – – ICPC2003-World :http://icpc.baylor.edu/icpc/Finals/Problems.html ICPC2002-Kaohsiung http://icpc.baylor.edu/past/icpc2003/Regionals/Reports/icpc.baylor.e du/icpc/regionals/Kaohsiun02/index.html 73 74