编程代考 COMP3121/9101 (Problem Set 5) School of Computer Science and Engineering, U

COMP3121/9101 (Problem Set 5) School of Computer Science and Engineering, UNSW Sydney List of Abbreviations and Symbols
A[1..n] An array indexed from 1 to n of n elements.
N Set of all natural numbers, i.e., {1, 2, 3, . . . }.
R Set of all real numbers.

Copyright By PowCoder代写 加微信 powcoder

Z Set of all integers, i.e., {…,−2,−1,0,1,2,…}. ∃ symbol meaning there exists.
∀ symbol meaning for all. Modifiers
To help you with what problems to try, problems marked with [K] are key questions that tests you on the core concepts, please do them first. Problems marked with [H] are harder problems that we recommend you to try after you complete all other questions (or perhaps you prefer a challenge). Good luck!!!
1 Optimisation problems
2 Enumeration problems
3 Knapsack and related problems
5 Shortest paths
2 11 15 16 20

COMP3121/9101 (Problem Set 5) School of Computer Science and Engineering, UNSW Sydney
§1 Optimisation problems
Exercise 1.1. [K] You are given n intervals on an axis. The ith interval [li,ri) has integer endpoints li < ri and has a score of si. Your task is to select a set of disjoint intervals with maximum total score. Note that if intervals i and j satisfy ri = lj then they are still disjoint. Design an algorithm which solves this problem and runs in O(n2) time. The input consists of the positive integer n, as well as 2n integers l1, r1, . . . , ln, rn and n positive real numbers s1, . . . , sn. The output is the set of intervals chosen, organised in any format or data structure. For example, if n = 4 and the intervals are: l1 = 0 l2 = 1 l3 = 2 l4 = 3 r1 = 3 r2 = 3 r3 = 4 r4 = 5 s1 = 2 s2 = 1 s3 = 4 s4 = 3 then you should select only the first and fourth intervals, for a maximum total score of 5. Note that interval 3 is not disjoint with any other interval. Solution. Sort the intervals by increasing order of endpoint ri and relabel accordingly. Henceforth we assume r1 ≤ . . . ≤ rn. We then proceed by dynamic programming. Subproblems: for 0 ≤ i ≤ n, let P (i) be the problem of determining opt(i), the maximum total score of a set of disjoint intervals where the last chosen interval is the ith, and m(i), the second largest interval index in one such set. If the set consists of only one interval, then m(i) will be zero. Recurrence: for 1 ≤ i ≤ n, and m(i) = argmax opt(j) j : rj ≤ li opt(i) = si + opt(m(i)). The solution for i must include interval i, so we extend the best solution with last chosen interval j finishing at or before the start of interval i. Base case: opt(0) = 0 and m(0) is undefined. Order of computation: subproblem P(i) depends only on earlier subproblems (P(j), where j < i), so we can solve the subproblems in increasing order of i. Final answer: The maximum total score is max opt(i). 1≤i≤n To recover the set which yields this score, we let i∗ = argmax opt(i), 1≤i≤n and backtrack through the m array to obtain the set {i∗, m(i∗), m(m(i∗)), . . .}. Time complexity: There are O(n) subproblems, each solved in O(n), and constructing the final answer also takes O(n). Thus the overall time complexity is O(n2). ■ 2 COMP3121/9101 (Problem Set 5) School of Computer Science and Engineering, UNSW Sydney Exercise 1.2. [K] Due to the recent droughts, n proposals have been made to dam the Murray river. The ith proposal asks to place a dam xi meters from the head of the river (i.e., from the source of the river) and requires that there is not another dam within ri metres (upstream or downstream). Design an algorithm that returns the maximal number of dams that can be built, you may assume that xi < xi+1 for all i = 1, . . . , n − 1. Subproblems: We can solve this problem by considering the subproblem P (i): For every i ≤ n, what is opt(i), the largest possible number of dams that can be built among proposals 1, . . . , i such that the ith dam is built. Base case: Our base case is then opt(1) = 1 as only dam 1 can be built. Recurrence: Our recurrence is then opt(i)=1+max{opt(j) : xi −xj >max(ri,rj)} j wi, dj > di}.
Order of subproblems: Subproblem P(i) depends on previous subproblems, so we compute these subprob- lems in increasing order of wi and di.
Final answer: The final solution is simply max1≤i≤6n opt(i).
Time complexity: Ordering the boxes using merge sort takes O(n log n) time. For the dynamic programming component, we have 6n subproblems and for each subproblem, we perform a O(n) search to find boxes whose base is large enough to stack the current box. Thus, we have an O(n log n) + O(6n2) = O(n2) algorithm. ■
Exercise 1.4. [K] You have n1 items of size s1 and n2 items of size s2. You would like to pack all of these items into bins, each of capacity C > s1, s2, using as few bins as possible. Design an algorithm that returns the minimal number of bins required.
Solution. Consider the following:
Subproblems: we consider the subproblems P (i, j) of finding opt(i, j), the minimal number of bins required
to pack i many items of size s1 and j many items of size s2.
Recurrence: For all 1 ≤ i ≤ n1 and all 1 ≤ j ≤ n2. Let C/s1 = K and opt(i,j) denote the solution to P (i, j), then our recurrence step is essentially an exhaustive search
􏰅 􏰁 􏰃 C − k s1 􏰄􏰂􏰆 opt(i,j)=1+ min opt i−k,j−
Then, we try all options of placing between 0 and K many items of size s1 into one single box and then fill the box to capacity with items of size s2, and optimally packing the remaining items by checking previous values of the subproblems.
Base case: We can compute the base case of opt(1,1) easily via considering the magnitude of s1,s2 and C. ORder of computation: We can compute the subproblems in increasing orders of j then i as each (i,j)
depends on earlier subproblems (similar to knapsack).
Final answer: The minimal number of bins is then just opt(n1,n2).
Time complexity: As for each (i,j) we consider K many possible placements, our algorithm runs in time O(K n1 n2) = O(C n1 n2).
Exercise 1.5. [K] Consider a row of n coins of values v1, v2, …vn, where n is even. We play a game against an opponent by alternating turns. In each turn, a player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the coin. Determine the maximum possible amount of money we can definitely win if we move first.
Note — Such an algorithm runs in exponential time in the size of the input, because input takes only O(log2 C + log2 n1 + log2 n2 + log2 s1 + log2 s2) many bits to represent.

COMP3121/9101 (Problem Set 5) School of Computer Science and Engineering, UNSW Sydney Solution. From this problem, we can see that dynamic programming has a very important role in the field
of game theory.
Subproblems: Let us consider the subproblem P (i, j): What is opt(i, j), the maximal amount of money we can definitely win if we play on the subsequence between coins at the position i and j. We also add the requirement that such that j − i + 1 is an even number and 1 ≤ i < j ≤ n. Recurrence: Our recurrence is then 􏰇vi +min{opt(i+2,j),opt(i+1,j−1)}, vj +min{opt(i+1,j−1),opt(i,j−2)} opt(i, j) = max The options inside the min functions represent the choice your opponent takes, either to continue taking from the same end as you took or from the opposite end of the sequence. Order of computation: The problems to find opt(i, j) are solved in order of the size of j − i. Final answer: The maximum amount of money we can win is opt(1, n). Time complexity: The total complexity is O(n2) as this is how many pairs of i,j we have and each stage of the recursion has only constant number of steps (4 table lookups and 2 additions plus two min and one max operations). ■ Exercise 1.6. [K] Given a sequence of n positive or negative integers A1,A2,...,An, determine a contiguous subsequence Ai to Aj for which the sum of elements in the subsequence is maximised. Subproblems: For each 1 ≤ i ≤ n, We solve the following subproblem P (i): what is opt(i), the maximum sum of elements ending with integer i? Base case: If there are no elements chosen, the maximum sum of elements is 0; hence, opt(0) = 0. Recurrence: Suppose that we have chosen the sequence of elements that ends in i − 1, this is what we compute when we compute opt(i − 1). Now, if we are forced to choose Ai (since we always end with integer i), either it’ll increase opt(i − 1) or Ai begins a new chain of elements. Thus, we have opt(i)=Ai +max(opt(i−1),0). To determine the contiguous subsequence, we also keep track of the start element; to do so, we solve the following recursive function. That is, for all 1 ≤ i ≤ n, 􏰇start(i − 1) if opt(i − 1) > 0,
start(i) =
i if opt(i−1)≤0.
Order of subproblems: Since each subproblem depends on the previous subproblems, we solve the subprob-
lems in increasing order of i.
Final answer: We can determine the end of the subsequence by solving the initial subproblems and returning
the index i such that max1≤i≤n opt(i). To return the contiguous subsequence, we return [start(i), i]. Time complexity: Each subproblem can be solved in O(1) since we just determine the maximum of opt(i−1)
and 0. There are n subproblems; therefore, the time complexity is O(n). ■

COMP3121/9101 (Problem Set 5) School of Computer Science and Engineering, UNSW Sydney
Exercise 1.7. [H] Skiers go fastest with skis whose length is close to their height. Consider n skiers with heights h1,h2,…,hn, gets a delivery of m ≥ n pairs of skis, with lengths l1,l2,…,lm. Design an algorithm to assign to each skier one pair of skis to minimise the sum of the absolute differences between the height hi of the skier and the length of the corresponding ski they got, i.e., to minimise
S = 􏰈 􏰀􏰀 h i − l s ( i ) 􏰀􏰀
where s(i) is the index of the skies assigned to the skier of height hi.
Solution. To start, we observe that
Proof. We produce a similar argument to Tutorial 3 question 4.6. As the |·| is the distance between 2 points on a number line, we can consider all possible orientation of hi,hj and ls(i),ls(j) and consider the sum of distance between them. After considering all orientations, we will see that swapping the assignment will always produce a lower or equal sum of difference. (try it yourself!!) ■
This implies that we may initially sort the skiers by height, sort the skis by length, and find some sort of pairing such that there are no crossovers. We now relabel the sorted height and skis as h1, h2, . . . , hn and l1,l2,…,lm.
Subproblems: Consider the following subproblem P (i, j): What is opt(i, j), the minimum cost of matching the first i skiers with the first j skies such that each of the first i skiers gets a ski?
Base case: Our base case is then for all i = j,
opt(i,i)=􏰈|hk −lk|
Claim — For any 2 skiers i and j with hi < hj, then our preferred assignment will have ls(i) < ls(j) (we call this the case of crossover). If this were not the case, we could swap the skis assigned to i and j, which would lower the sum of differences. as this this the case of i skiers are “forced” to pick i skis. Recurrence: Our recurrence for j > i is then
opt(i, j) = min {opt(i, j − 1), opt(i − 1, j − 1) + |hi − lj |} as we consider assigning the skier i with lj and picking the more optimal option.
Order of computation: Note that for this recurrence we need to again be careful of the order of computation for our subproblems. For the discrete grid domain of opt(·), for each (i, j), we require (i, j−1) and (i−1, j−1). Therefore, one such valid order is to compute the subproblems in increasing order of j then increasing order of i.
Final answer: We can now use this value to compute our assignment, by starting at (i, j) = (n, m), we start at (i, j) where i = n and j = m. If opt(i − 1, j − 1) + |hi − lj | < opt(i, j − 1) then s(i) = j and we try again at (i − 1, j − 1). Otherwise, we try again at (i, j − 1). If at any point we reach i = j (our base case), we simply assign s(k) = k for all 1 ≤ k ≤ i. Time complexity: The complexity of our recurrence is then O(nm) for all i, j until opt(n, m). The complexity of retrieval is O(m), as each step of our retrieval, j decreases by exactly 1. The total complexity of our algorithm is then O(mn). COMP3121/9101 (Problem Set 5) School of Computer Science and Engineering, UNSW Sydney Exercise 1.8. [H] You have been handed responsibility for a business in Texas for the next n days. Initially, you have K illegal workers. At the beginning of each day, you may hire an illegal worker, keep the number of illegal workers the same or fire an illegal worker. At the end of each day, there will be an inspection. The inspector on the ith day will check that you have between li and ri illegal workers (inclusive). If you do not, you will fail the inspection. Design an algorithm that determines the fewest number of inspections you will fail if you hire and fire illegal employees optimally. Solution. We start by noticing that: Subproblems: we can consider the subproblem P (i, j): What is opt(i, j), the minimum number of inspections I have failed on day i assuming that on that day I have j many illegal workers? Base case: Our base case is opt(0,K) = 0, since we start with 0 failed inspections before the first day begins. Recurrence: Our recurrence for 1 ≤ i ≤ n and all j such that max(0, K − i) ≤ j ≤ K + i, opt(i−1,j−1) ifj−1≥max(0,K−(i−1))), opt(i, j) = failed(i, j) + min opt(i − 1, j), opt(i−1,j+1) ifj+1≤K+i−1. Here, failed(i,j) returns 1 if the j falls out of the range of [li,ri], and returns 0 otherwise. Note that the first option in the cases corresponds to hiring an illegal worker on the morning of day i, providing that the number of workers the second corresponds to keeping the same number of illegal workers as on the previous day and the third option corresponds to firing a worker from the previous day. Order of computation: we can compute the subproblems in increasing order of j then i. Final answer: The final answer is then min{opt(n,j):max(K−n,0) ≤ j ≤ K+n}. Time complexity: The total complexity is O(n2), as there are n days, and at most 2n + 1 possible values of illegal worker each day. ■ Exercise 1.9. [H] A company is organising a party for its employees. The organisers of the party want it to be a fun party, and so have assigned a fun rating to every employee. The employees are organised into a strict hierarchy, i.e. a tree rooted at the president. There is one restriction, though, on the guest list to the party: an employee and their immediate supervisor (parent in the tree) cannot both attend the party (because that would be no fun at all). Give an algorithm that makes a guest list for the party that maximises the sum of the fun ratings of the guests. Solution. Suppose that T(i) defines the subtree of the tree T of all employees that is rooted by employee i. Then, for each subtree, we will look at the maximum sum of the fun ratings in two ways: one which includes employee i and one that does not include employee i. For each subtree, we define the following quantities: • I(i) is the maximal sum of fun factors fun(i) that satisfies all of the constraints but includes root i, Note — Minimum and maximum illegal workers you could possible have on the evening of day i are max(K −i,0) and K +i. COMP3121/9101 (Problem Set 5) School of Computer Science and Engineering, UNSW Sydney • E(i) is the maximal sum of fun factors fun(i) that satisfies all of the constraints but excludes root i. With these quantities defined, we now perform the dynamic programming approach. Subproblems: We solve the following subproblem P(i): What is opt(i), the maximum sum of the fun ratings of T(i)? Base case: For each i that is a leaf node, opt(i) = fun(i). Recursion: For the recursion, we need to compute two quantities, I(i) and E(i). For each non-leaf node, we need to consider excluding the subordinates (because i is the immediate supervisor of these workers) if we choose to include employee i, or if we exclude i, then we can either choose to exclude the children or include the children of i, whichever value is greater. Thus, we compute I(i) by I(i) = fun(i) + 􏰈 E(jk), 1≤k≤m where j1, . . . , jm are the subordinates of i. We compute E(i) by E(i) = 􏰈 max (I(jk), E(jk)) , 1≤k≤m where j1, . . . , jm are defined as above. In this way, for each child of i, we can either include them or exclude them. Then solving P(i) is simply a matter of max(I(i),E(i)). Order of subproblems and Final answer: We solve the subproblems from the leaves of the tree to the root of the leaves, where the final solution is simply opt(n) = max(I(n), E(n)) where n is the root of the tree. Time complexity: The time complexity is linear in the number of employees because we only need to scan through each of the employees once. Each employee only has one parent. In the worst case, we need to ask every employee exactly once. ■ Exercise 1.10. [H] You have to cut a wood stick into several pieces. The most affordable company, Analog Cutting Machinery (ACM), charges money according to the length of the stick being cut. Their cutting saw allows them to make only one cut at a time. It is easy to see that different cutting orders can lead to different prices. For example, consider a stick of length 10 m that has to be cut at 2, 4, and 7 m from one end. There are several choices. One can cut first at 2, then at 4, then at 7. This leads to a price of 10 + 8 + 6 = 24 because the first stick was of 10 m, the resulting stick of 8 m, and the last one of 6 m. Anotherchoicecouldcutat4,thenat2,thenat7. Thiswouldleadto 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com