构造上下文无关文法:求解语言L={a^m b^m c^k | k ≤ m}的CFG
Hey there! Let's work through constructing a context-free grammar (CFG) for the language ( L = { a^m b^m c^k \mid k \leq m } ) and prove it's a context-free language.
First, let's unpack the language's structure: every valid string has a block of as, followed by exactly the same number of bs, then a block of cs where the count of cs is no greater than the count of as (or bs, since they're equal). The core trick is making sure we can't generate more cs than we have a-b pairs.
We need rules that tie the generation of cs directly to the a-b pairs, so cs can never outnumber them. Here's a working grammar:
S → ε S → aSb S → aSbc
Let's break down each production rule:
S → ε: Generates the empty string, which fits ( L ) when ( m=0 ) and ( k=0 ) (since ( 0 \leq 0 )).S → aSb: Adds oneato the front and onebto the end, increasing ( m ) by 1 while keeping ( k=0 ). Repeat this to build ( a^m b^m ) with nocs.S → aSbc: Adds oneato the front, onebto the middle, and onecto the end. Each use increases both ( m ) and ( k ) by 1, ensuring ( k ) never surpasses ( m ).
Let's test some valid cases to confirm:
- For ( m=2, k=0 ): Apply
S → aSbtwice, thenS → ε:S → aSb → a(aSb)b → aaεbb → aabb(valid) - For ( m=2, k=1 ): Apply
S → aSbonce,S → aSbconce, thenS → ε:S → aSb → a(aSbc)b → a(aεbc)b → aabbc(valid) - For ( m=3, k=3 ): Apply
S → aSbcthree times, thenS → ε:S → aSbc → a(aSbc)bc → a(a(aSbc)bc)bc → aaaεbbbccc → aaabbbccc(valid)
Invalid strings (like aabbccc where ( k=3 > m=2 )) can't be generated—every c requires a matching a and b to be added at the same time, so ( k ) can never exceed ( m ).
By definition, a language is context-free if there exists a context-free grammar that generates it. Since we've constructed a valid CFG for ( L ), this formally proves ( L ) is a context-free language.
内容的提问来源于stack exchange,提问作者Melissa

