270 likes | 346 Views
Applied Algorithms. Lecture # Backtracking. Announcements. ACM Student Chapter Meeting Where: FAB-150. Fourth Avenue Building, across the hallway from the Linux Lab When: Wednesday, June 1. 11:30AM Topic: Become an Undergrad Researcher at PSU! Final Exam Date
E N D
Applied Algorithms Lecture # Backtracking
Announcements • ACM Student Chapter Meeting • Where: FAB-150. Fourth Avenue Building, across the hallway from the Linux Lab • When: Wednesday, June 1. 11:30AM • Topic: Become an Undergrad Researcher at PSU! • Final Exam Date • Monday, June 6, 2005 • 12:30 – 14:20 PM
Checking for primality Bool prime(int n) // test for primality of n { int i; int m; if (n==2) return TRUE; if (n<2) return FALSE; m = sqrt(n)+1; for (i=2;i<=m;i++) if (n%i == 0) return FALSE; return TRUE; }
Sum of 4 primes • Why won’t this work? for (i=2, i<=n, i++) if (prime(i)) for (j=2, j<=n, j++) if (prime(j)) for (k=2, k<=n, k++) if (prime(k)) for (l=2, l<=n, l++) if (prime(l)) if (i+j+k+l=target) printf(“%ld %ld %ld %ld\n”,I,j,k,l)
What if we looped over just primes • Precompute all the primes from 1 to target • Int primes[size] • Void initPrimes(int largest) • { …} How many primes are there between 1 and 10,000,000 ?
Lets explore? int countPrimes(int n) { int i; int count; count = 0; for (i=2;i<=n;i++) { if (prime(i)) count++; if (i%100000 == 0) printf("i= %ld, num primes= %ld\n",i,count); } printf("num primes= %ld density= %ld\n",count,n/count); }
Analyze • Are there a lot of primes? • What’s the average distance between primes? • Is this number big? • Does this suggest a solution?
Largest distance between primes int enumerate(int n) { int i; int count; int last; int maxdif; count = 0; last = 2; maxdif = 0; for (i=3;i<=n;i++) { if (prime(i)) { count++; maxdif = max(i-last,maxdif); last = i;}; if (i%100000 == 0) printf("i= %ld, num primes= %ld, maxdif= %ld\n“ ,i,count,maxdif); } }
Can we find 3 primes? • Why is this more feasible? • Should be easy to find 3 primes that add up to a small integer since we need only loop through primes up to that integer. • If max=154, how many small primes will we need?
int firstThirty() { int i; int count; count = 0; for (i=2;count<30;i++) if (prime(i)) { count++; printf("%ld,",i);}; }
Strategy /* An array of the first 30 small primes */ int sp[30] = {2,3,5,7,11,13,17,19,23,29,31,37,41 ,43,47,53,59,61,67,71,73,79,83,89,97 ,101,103,107,109,113}; int ps[200][3]; /* ps[6] = {2,2,2} ps[i] stores 3 primes that add up to i ps[7] = {2,2,3} ps[8] = {2,3,3} . . . ps[199]= {3,83,113} */
Computing ps int init_ps_sub(n) { int j; int k; int l; for (j=0;j<30;j++) // Find 3 small primes for (k=0;k<30;k++) // such that p1+p2+p3 = n for (l=0;l<30;l++) // store them in the "ps" array if (sp[j]+sp[k]+sp[l]==n) { ps[n][0] = sp[j]; ps[n][1] = sp[k]; ps[n][2] = sp[l]; return 0;}; printf("Can't find 3 small primes for %ld\n",n); }
Computing 4 primes int test(int n) { int i; int diff; if (n<8) { printf("Imposible\n"); return 0; } for (i=n-6; i>=2; i--) // find largest prime at least if (prime(i)) // 6 less than n, call it "i" { diff = n-i; // then lookup 3 small primes printf("%ld %ld %ld %ld\n“ ,i,ps[diff][0],ps[diff][1] ,ps[diff][2]); return 0; } }
In Class Problems • Queue 8.6.3 • Page 179 of the text • We will discuss this in class
Queues of N people of different height How can we count how many can see to the left? To the right?
Problem • Given a queue of fixed size N. • A fixed number of people who can see to the left. • A fixed number of people who can see to the right. • How many way can we arrange the N people to get the matching left and right counts?
Solution? • Compute all possible ways to arrange N people. • Throw away those that don’t have the correct left and right count. • Arranging things in different order is called a permutation.
Computing permutations • What are the permutations of [1,2,3] ? • Chose an element. • Choices are 1, 2, or 3 • For each choice prepend it to the permutations of what’s left after removing the choice. • Candidates [1,2,3] • (1,[2,3]) (2,[1,3]) (3,[1,2]) • What are the permutations of [2,3]? • [2,3] and [3,2]
Permutations [1,2,3] = candidates = (1,[2,3]) (2,[1,3])(3,[1,2]) permutations [2,3] = [2,3], [3,2] [1,3] = [1,3],[3,1] [1,2] = [1,2],[2,1] [1,2,3] [1,3,2] [2,1,3],[2,3,1] [3,1,2],[3,2,1]
candidates xs = f [] xs where f before (choice:after) = (choice,reverse before++after) : (f (choice:before) after) f before [] = [] gen2 :: [Int] -> [Int] -> [[Int]] -> [[Int]] gen2 chosen [] all = (reverse chosen):all gen2 chosen toAdd all = add pairs all where pairs = candidates toAdd add [] all = all add ((choice,remains):pairs) all = add pairs (gen2 (choice:chosen) remains all)
How many permutations are there? • [1,2,3,4] • 4 choices • For each choice we prepend it to the permutations of list of size three. • Perms([ ]0) = 1 (the empty sequence) • Perms([ ]x+1) = (x+1) * Perms([ ]x) • Perms([ ]n) = n!
We need some trick • Find the tallest person, and then break it into 2 sub problems. Where can the tallest person be given left and right numbers?
Bounding the tallest • If left = n, then tallest must be at position at least n, • If right = m, then tallest must be at position at most Max-m+1 • So tallest must be between Left tallest N-Right+1 Left=3 Right=3
Solving the sub problem • k = exact number of views to the left required • n = size of the permutation required • chosen is the prefix of the permutation so far • remains = the set left to choose the next element from p2 k n chosen remains all | length chosen == n = (reverse chosen,remains):all | True = add pairs all where pairs = candidates remains add [] all = all add ((x,rs):pairs) all = let next = (x:chosen) in if (possible k n next) then (p2 k n next rs (add pairs all)) else (add pairs all)
What’s possible? • Sometimes we know a chosen sequence can’t lead to a good solution. possible k n xs = viewl <= k && viewl + n - len >= k where len = length xs viewl = countRight xs
All possible winners try2 n left right | n+1 < left+right = [] | True = concat (map each positionsN) where positionsN = [left .. n - right + 1] each i = concat(map f leftChoices) where leftChoices = p2 (left-1) (i-1) [] [1..n-1] [] f (lefts,remains) = concat(map add (p2 (right-1) (n-i) [] remains [])) where add (rights,_) = [lefts ++ [n] ++ reverse rights]
Today’s Assignments Read for next time Chapter 9 of the text. pp 188-218 Be prepared to answer questions in class next Friday from the reading. Programming assignment • 8.6.8 Bigger Square Please • Page 186 • Write a solution Submit your solution (until you get it right) Hand in both your program, and the judge output. Those who volunteer to discuss their program get class participation points. Email me solutions before noon on Friday, May 6.