You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

构造上下文无关文法:求解语言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.


Step 1: Build the Valid CFG

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 one a to the front and one b to the end, increasing ( m ) by 1 while keeping ( k=0 ). Repeat this to build ( a^m b^m ) with no cs.
  • S → aSbc: Adds one a to the front, one b to the middle, and one c to the end. Each use increases both ( m ) and ( k ) by 1, ensuring ( k ) never surpasses ( m ).

Step 2: Verify the Grammar Works

Let's test some valid cases to confirm:

  • For ( m=2, k=0 ): Apply S → aSb twice, then S → ε:
    S → aSb → a(aSb)b → aaεbb → aabb (valid)
  • For ( m=2, k=1 ): Apply S → aSb once, S → aSbc once, then S → ε:
    S → aSb → a(aSbc)b → a(aεbc)b → aabbc (valid)
  • For ( m=3, k=3 ): Apply S → aSbc three times, then S → ε:
    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 ).


Step 3: Prove L is Context-Free

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:39:29