100 likes | 163 Views
Proof: Let G be a Chomsky normal form grammar for language L. The following O(n 3 ) algorithm decides whether G accepts w , where n is the length of w :. Theorem 7.16: Every CFL is a member of P. 1. If w = and S → is a rule, accept.
E N D
Proof: Let G be a Chomsky normal form grammar for language L. The following O(n3) algorithm decides whether G accepts w, where n is the length of w : Theorem 7.16: Every CFL is a member of P
1. If w = and S → is a rule, accept. 2. For i = 1 to n: // examine each substring of length one 3. For each variable A: 4. Test whether A →bis a rule, whereb = wi. 5. If so, place A in table (i, i). 6. For l = 2 to n: // l is the length of the substring 7. For i = 1 to n – l + 1: // i is the start position of the substring 8.Let j = i + l – 1 // j is the end position of the substring 9. For k = i to j – 1 // k is the split position 10. For each rule A →BC 11. If table (i, k) contains B and table (k+1, j) contains C, put A in table (i, j) 12. If S is in table (1, n), accept; otherwise, reject O(n3) Parsing Algorithm (Dynamic Programming)
1. If w = and S → is a rule, accept. 2. For i = 1 to n: // examine each substring of length one 3. For each variable A: 4. Test whether A →bis a rule, whereb = wi. 5. If so, place A in table (i, i). 6. For l = 2 to n: // l is the length of the substring 7. For i = 1 to n – l + 1: // i is the start position of the substring 8.Let j = i + l – 1 // j is the end position of the substring 9. For k = i to j – 1 // k is the split position 10. For each rule A →BC 11. If table (i, k) contains B and table (k+1, j) contains C, put A in table (i, j) 12. If S is in table (1, n), accept; otherwise, reject Why is it O(n3) ? Each of steps 6, 7, 9 runs at most n times:
Example • Consider L = anbn • Familiar grammar is S → ASB | • Convert to CNF: S0→ AB | CB | C → AS S → CB | AB A → a B → b • Try w = aabb • |w| = 4, so table will be 4 4:
2. For i = 1 to n: 3. For each variable A: 4. Test whether A →bis a rule, whereb = wi. 5. If so, place A in table (i, i). A → a B → b
6. For l = 2 to n: // l is the length of the substring 7. For i = 1 to n – l + 1: // i is the start position of the substring 8.Let j = i + l – 1 // j is the end position of the substring 9. For k = i to j – 1 // k is the split position lijk 2 1 2 1 2 2 3 2 2 3 4 3 3 1 3 1 3 1 3 2 3 2 4 2 3 2 4 3 4 1 4 1 4 1 4 2 4 1 4 3
10. For each rule A →BC 11. If table (i, k) contains B and table (k+1, j) contains C, put A in table (i, j) S0→ AB • S0→ CB C → AS S → AB • S → CB ikk+1 jtable(i, k)table(k+1, j) 2 2 3 3 AB
10. For each rule A →BC 11. If table (i, k) contains B and table (k+1, j) contains C, put A in table (i, j) S0→ AB • S0→ CB C → AS S → AB • S → CB ikk+1 jtable(i, k)table(k+1, j) 1 1 2 3 AS
10. For each rule A →BC 11. If table (i, k) contains B and table (k+1, j) contains C, put A in table (i, j) S0→ AB • S0→ CB C → AS S → AB • S → CB ikk+1 jtable(i, k)table(k+1, j) 1 3 4 4 CB