题解:P15480 [CERC2012] Word equations

· · 题解

[CERC2012] Word equations 题解

题目链接

背景

本题是 [CERC2012] 的一道题目,同时,如 qiuzhouyiiii 所述,本道题是某次集训中一场模拟赛的 T3,虽然题面被爆改了导致我一开始都没看到什么关联性,我也场切并在洛谷 AC 了这道题,所以来写篇题解。

题目大意

给定一排形如 A = Word 或 A = B + C 的替换方程,无环且不重复。现在给定一个起始符号 S 和一个作为模式的单词 P(其中长度 |P| \in (0, 2000]),问 S 最终展开得到的炒鸡长字符串中,是否存在一个子序列等于 P。

思路

:::epigraph[——qiuzhouyiii] 注意到这个所谓的方程系统有点像树,考虑特殊 DAG. :::

做完了就觉得很明显是 DAG。可是——

为什么会想到 DAG?

Idea 1 (0pts):

我们可以先这么想:我们是否可以暴力直接构造 S 展开后的原字符串?

最直观的想法就是:既然题目给了变量替换方程,我们就写一个递归函数 expand(u),将 S 递归展开成纯小写字母字符串 T,然后双指针在 T 中匹配模式串 P。

Code:

#include<bits/stdc++.h>  
using namespace std;   

const int MAXN=505;   
const int MAXM=2005;   

struct Node{   
    int type;   
    string str;   
    int b,c;   
}node[MAXN];   

string p;   
int m;   

// 递归直接构造展开后的原字符串
string expand(int u){   
    if(node[u].type==0){ 
        return node[u].str; 
    } 
    return expand(node[u].b)+expand(node[u].c); 
}   
void solve(){   
    int k;   
    cin>>k;   
    unordered_map<string, int> mp;   
    int tot=0;   
    auto get_id=[&](const string& s){   
        if(!mp.count(s)) mp[s]=++tot;   
        return mp[s];   
    };   
    string input;   
    getline(cin,input);   
    for(int i=0;i<k;i++){   
        getline(cin,input);   
        while(input.empty()) getline(cin,input);   
        vector<string> vec; 
        string tmp=""; 
        for(char ch:input){ 
            if(ch==' '||ch=='\r'||ch=='\t'||ch=='\n'){ 
                if(!tmp.empty()){ 
                    vec.push_back(tmp); 
                    tmp=""; 
                } 
            }else{ 
                tmp+=ch; 
            } 
        } 
        if(!tmp.empty()) vec.push_back(tmp); 
        int u=get_id(vec[0]); 
        if(vec.size()==5){ 
            node[u].type=1; 
            node[u].b=get_id(vec[2]); 
            node[u].c=get_id(vec[4]); 
        }else{ 
            node[u].type=0; 
            node[u].str=vec[2]; 
        } 
    }   
    string start_sym; 
    cin>>start_sym>>p; 
    m=p.length(); 
    if(!mp.count(start_sym)){ 
        cout<<"NO\n"; 
        return; 
    } 
    int start_id=mp[start_sym]; 
    string T=expand(start_id); 
    int idx=0; 
    for(char ch:T){ 
        if(idx<m&&ch==p[idx]) idx++; 
    } 
    if(idx==m){ 
        cout<<"YES\n"; 
    }else{ 
        cout<<"NO\n"; 
    } 
}   

int main(){   
    ios_base::sync_with_stdio(false);   
    cin.tie(nullptr);   
    int t;   
    cin>>t;   
    while(t--){   
        solve();   
    }   
    return 0;   
} 

Result: TLE。

为什么会 TLE?

因为这个代码是复杂度 O(2^k) 的。

考虑如下构造的极端数据:

A_1 = "a" A_2 = A_1 + A_1 \quad (|A_2| = 2) A_3 = A_2 + A_2 \quad (|A_3| = 4) \dots A_k = A_{k-1} + A_{k-1} \quad (|A_k| = 2^{k-1})

当 k = 500 时,最终生成的字符串 T 的长度将达到 2^{499},这肯定是不能过的。

Idea 2:

在尝试了暴力解法后,我们意识到暴力是不可行的了,那该怎么办?

观察暴力过程,可以发现递归函数每次返回的字符串都将是巨大的,这意味着某个特殊符号 u 如果出现了多次,那么同一个巨大的字符串就会被构造多次。

可是思考一个核心问题:在子序列匹配时,我们需要知道符号 u 展开后的具体字符是什么吗?

答案是不需要。因为题中的匹配只在乎从模式 P 的第 pos 位开始,匹配完符号 u 代表的所有字符后,模式 P 的匹配推进到了什么位置,而不关心里面的具体字符。

所以此时可以考虑 DP。

考虑判定这些子序列的贪心性质:

在字符串中匹配 P 的字符时,能尽早匹配肯定要尽早匹配,这样给后面的人匹配的空间就会更大,结果就肯定比你一直在那里便秘更优。

::::info[证明]

设模式串 P 的长度为 m,展开后的目标字符串为 T,其长度为 n。

定义 P = p_1 p_2 \dots p_m。

定义 T = t_1 t_2 \dots t_n。

定义 M_{valid} 为一个子序列匹配方案可以表示为一个严格递增的下标序列

此时命题为: > 若 $T$ 中 $\exists I = (i_1, i_2, \dots, i_m) \in M_{valid}$,那么取 $p_1$ 在 $T$ 中最早出现的位置 $i'_1 = \min \{ j \mid t_j = p_1 \}$,也**一定能**构成 $I' = (i'_1, i_2, \dots, i_m) \in M_{valid}$。 --- 假设已知存在一个合法匹配序列: $$I = (i_1, i_2, \dots, i_m)

根据 i'_1 的定义,它是 p_1 在 T 中首次出现的下标,因此必然满足:

i'_1 \le i_1

我们构造一个新的下标序列 I',仅将 I 的第一个元素 i_1 替换为 i'_1:

I' = (i'_1, i_2, i_3, \dots, i_m)

由于 t_{i'_1} = p_1,且 \forall k \in \{2, 3, \dots, m\} 有 t_{i_k} = p_k,因此所有字符依然正确匹配,且:

因此构造出的新序列 I' 依然是一个合法的匹配序列。

同理:

假设我们已经贪心匹配了前 k-1 个字符,所选的最早下标依次为 i'_1 < i'_2 < \dots < i'_{k-1}。 对于第 k 个字符 p_k:

这样就可以证明这个贪心性质了。

::::

因此可以注意到方程组构成了一个 DAG,我们可以直接在 DAG 上跑记忆化搜索。

如果设 f_u 为 u 点最多匹配模式 P 的位数,在遇到复合方程 A = B + C 时,你就会大脑宕机了。

如果你灵机一动,去设 f_{u, i, j} 表示 u 点能否匹配模式 P 的 [i, j] 区间。对于 A = B + C 型方程,只需枚举点 k 使得 f_{B, i, k} \land f_{C, k+1, j} 为真即可,确实非常好转移,是一个区间 DP。

但这样设计状态,时间复杂度会达到 O(N \cdot |P|^2) 甚至 O(N \cdot |P|^3),还是 喜提 MLE。

::::error[MLE Code]

#include <bits/stdc++.h>
using namespace std; 

const int MAXN=505; 
const int MAXM=2005; 

struct Node{ 
    int type; 
    string str; 
    int b,c; 
}node[MAXN]; 

bool f[MAXN][MAXM][MAXM]; 
bool vis[MAXN][MAXM][MAXM]; 
string p; 
int m; 

bool dp(int u,int i,int j){ 
    if(i>j)return true; 
    if(vis[u][i][j])return f[u][i][j]; 
    vis[u][i][j]=true; 
    if(node[u].type==0){ 
        int cur=i; 
        for(char ch:node[u].str){ 
            if(cur<=j&&p[cur]==ch)cur++; 
        } 
        return f[u][i][j]=(cur>j); 
    }else{ 
        int b=node[u].b,c=node[u].c; 
        for(int k=i-1;k<=j;k++){ 
            if(dp(b,i,k)&&dp(c,k+1,j)){ 
                return f[u][i][j]=true; 
            } 
        } 
        return f[u][i][j]=false; 
    } 
} 

void solve(){ 
    int k; 
    cin>>k; 
    unordered_map<string,int> mp; 
    int tot=0; 
    auto get_id=[&](const string& s){ 
        if(!mp.count(s))mp[s]=++tot; 
        return mp[s]; 
    }; 
    string input; 
    getline(cin,input); 
    for(int i=0;i<k;i++){ 
        getline(cin,input); 
        while(input.empty())getline(cin,input); 
        vector<string> vec; 
        string tmp=""; 
        for(char ch:input){ 
            if(ch==' '||ch=='\r'||ch=='\t'||ch=='\n'){ 
                if(!tmp.empty()){ 
                    vec.push_back(tmp); 
                    tmp=""; 
                } 
            }else{ 
                tmp+=ch; 
            } 
        } 
        if(!tmp.empty())vec.push_back(tmp); 
        int u=get_id(vec[0]); 
        if(vec.size()==5){ 
            node[u].type=1; 
            node[u].b=get_id(vec[2]); 
            node[u].c=get_id(vec[4]); 
        }else{ 
            node[u].type=0; 
            node[u].str=vec[2]; 
        } 
    } 
    string start_sym; 
    cin>>start_sym>>p; 
    m=p.length(); 
    if(!mp.count(start_sym)){ 
        cout<<"NO\n"; 
        return; 
    } 
    int start_id=mp[start_sym]; 
    for(int u=1;u<=tot;u++){ 
        for(int i=0;i<m;i++){ 
            for(int j=0;j<m;j++){ 
                vis[u][i][j]=false; 
            } 
        } 
    } 
    if(dp(start_id,0,m-1)){ 
        cout<<"YES\n"; 
    }else{ 
        cout<<"NO\n"; 
    } 
} 

int main(){ 
    ios_base::sync_with_stdio(false); 
    cin.tie(nullptr); 
    int t; 
    cin>>t; 
    while(t--){ 
        solve(); 
    } 
    return 0; 
} 

::::

注意:读到这,请停下来自行思考一下如何设计状态以及 DP 的实现方式,想到了实现方式 / 真的想不出来再打开折叠框。

::::info[DP实现] 设 f_{u, i} 表示:从模式 P 的下标 i 开始,完全匹配完符号 u 所代表的完整字符串后,在 P 中能到达的最远匹配位置。 对于基础方程 A=str: 直接拿 str 中的字符顺次去匹配 P。若能匹配上,指针往后移动,最后返回移动后的指针位置。

对于复合方程 A = B + C: 先匹配 B,假设匹配完 B 后指针达到了 mid;再从 mid 开始匹配 C。最终得到的指针位置即为 f_{A, i} 的结果。 即:

f_{A, i} = f_{C, f_{B, i}}

当匹配指针 pos \in [|P|, \infty) 时,说明模式 P 已全部匹配成功,直接返回 |P| 即可,无需继续递归。 :::: 听完 / 想出这个实现后,如果这道题在你的水平范围之内的话,你应该就会写 80% 的代码了,剩下的一些边界情况见代码。

AC Code

#include<bits/stdc++.h>
using namespace std; 

const int MAXN=505; 
const int MAXM=2005; 

struct Node{ 
    int type;  // type = 0 表示基础方程 A = str;type = 1 表示复合方程 A = B + C
    string str; // 基础方程对应的纯字母字符串 str
    int b,c;   // 复合方程对应的左右子节点编号 (B 和 C) 
}node[MAXN]; 

int f[MAXN][MAXM]; 
string P; 
int m;    

// 记忆化搜索
int dfs(int u,int i){ 
    // 剪枝:若指针 i 已到达/超过 m,说明模式串 P 已完全匹配成功,直接返回 m
    if(i>=m) return m; 
    // 记忆化数组剪枝
    if(f[u][i]!=-1) return f[u][i]; 
    int cur=i; 
    if(node[u].type==0){ 
        // 基础方程 A = str
        for(char ch:node[u].str){ 
            if(cur<m&&P[cur]==ch) cur++; 
        } 
    }else{ 
        // 复合方程 A = B + C
        cur=dfs(node[u].b,cur); 
        // 得到最终的最远指针位置
        cur=dfs(node[u].c,cur); 
    } 
    // 记录并返回
    return f[u][i]=cur; 
} 

void solve(){ 
    int k; 
    cin>>k; 
    unordered_map<string, int> mp; 
    int tot=0; 
    auto get_id=[&](const string& s){ 
        if(!mp.count(s)) mp[s]=++tot; 
        return mp[s]; 
    }; 
    string input; 
    getline(cin,input); 
    // 解析 k 个替换方程
    for(int i=0;i<k;i++){ 
        getline(cin,input); 
        while(input.empty()) getline(cin,input); 
        vector<string> vec; 
        string tmp=""; 
        for(char ch:input){ 
            if(ch==' '||ch=='\r'||ch=='\t'||ch=='\n'){ 
                if(!tmp.empty()){ 
                    vec.push_back(tmp); 
                    tmp=""; 
                } 
            }else{ 
                tmp+=ch; 
            } 
        } 
        if(!tmp.empty()) vec.push_back(tmp); 

        int u=get_id(vec[0]); 
        if(vec.size()==5){ 
            // 复合方程 A = B + C
            node[u].type=1; 
            node[u].b=get_id(vec[2]); 
            node[u].c=get_id(vec[4]); 
        }else{ 
            // 基础方程 A = str
            node[u].type=0; 
            node[u].str=vec[2]; 
        } 
    } 
    string S; // 起始符号 S
    cin>>S>>P; 
    m=P.length(); 
    // 若起始符号 S 未在方程组左侧出现过,直接输出 NO
    if(!mp.count(S)){ 
        cout<<"NO\n"; 
        return; 
    } 
    int start_id=mp[S]; 
    for(int i=1;i<=tot;i++){ 
        memset(f[i],-1,sizeof(int)*(m+1)); 
    } 
    if(dfs(start_id,0)==m){ 
        cout<<"YES\n"; 
    }else{ 
        cout<<"NO\n"; 
    } 
} 

int main(){ 
    ios_base::sync_with_stdio(false); 
    cin.tie(nullptr); 
    int t; 
    cin>>t; 
    while(t--){ 
        solve(); 
    } 
    return 0; 
} 

复杂度 O(N \cdot |P|)。