Hong Kong Olympiad in Informatics 2006 Senior Problem
Hong Kong Olympiad in Informatics 2006 Senior Problem 1 Three Little Pigs Solution Guide by Eddy Chan 7/1/2006
Three Little Pigs Problem Description • Given: – Mother Pig has N bags of new bricks. – Each little pigs have created M designs, each requiring a specific number of bags. • Target: – Each little pig has to pick one of his designs, so that the total number of bags used for the three designs is maximized, while not exceeding N
Conversion of the Problem • Given: – N – 3 lists, each contains M numbers • Target: – Pick one number from each list, so that the total is maximized and ≤ N Notes: The problem can be simplified into 4 lines.
Example • N=14, M=4 – 1 5 8 10 – 2567 – 1 5 9 10
Solution (1) • Exhaustion SUM: =0 for i: =1 to M do for j: =1 to M do for k: =1 to M do if (list 1[i]+list 2[j]+list 3[k] <=N and larger than SUM) then SUM: =list 1[i]+list 2[j]+list 3[k] and store the 3 numbers Notes: Exhaustion is the first thing to think.
Solution (2) • Exhaustion + Binary Search SUM: =0 for i: =1 to M do for j: =1 to M do begin k: =binary_search(N-list 1[i]-list 2[j]) if (list 1[i]+list 2[j]+list 3[k] <=N and larger than SUM) then SUM: =list 1[i]+list 2[j]+list 3[k] and store the 3 numbers end Notes: binary_search(n) is a function to find the position of a number in list 3 that has the largest value ≤ n. If there is no such number, it will return the value 1
Solution (3) • Exhaustion + Linear Search SUM: =0 for i: =1 to M do begin k: =M; for j: =1 to M do begin while (k>1 and list 1[i]+list 2[j]+list 3[k]>N) do k: =k-1; if (list 1[i]+list 2[j]+list 3[k] <=N and larger than SUM) then SUM: =list 1[i]+list 2[j]+list 3[k] and store the 3 numbers end
Constraints In all the test cases, 1 ≤ N ≤ 30000; 1 ≤ M ≤ 3000; 1 bag ≤ amount of bricks required by any design ≤ 10000 bags In 50% of the test cases, 1 ≤ N ≤ 30000; 1 ≤ M ≤ 100; 1 bag ≤ amount of bricks required by any design ≤ 10000 bags Notes: Be careful of overflow
Constraints In all the test cases, M ≤ 3000 In 50% of the test cases, M ≤ 100 Exhaustion O(M 3) for i: =1 to M do for j: =1 to M do for k: =1 to M do if …. . then …… Exhaustion + Binary Search O(M 2 log M) for i: =1 to M do for j: =1 to M do begin k: =binary_search(N-list 1[i]-list 2[j]) if …. . then …. . end Exhaustion + Linear Search O(M 2) for i: =1 to M do begin k: =M; for j: =1 to M do begin while (k>1 and list 1[i]+list 2[j]+list 3[k]>N) do k: =k-1 if …. . then …. . end
More Comments • Sorting • Base Case, such as M=1
- Slides: 10