[BZOJ2882][后缀自动机]工艺

本文介绍了一种利用后缀自动机解决特定字符串处理问题的方法。通过构建双倍序列的后缀自动机,并采用贪心策略选取路径,最终求解出最短匹配路径。文章包含完整的C++代码实现,适用于需要高效字符串搜索的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

后缀自动机裸题
将序列复制两遍建后缀自动机
每次贪心地走最小的边
走N次得到答案

#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <map>
#define N 1000010

using namespace std;

struct SAM_{
    int fail[N],stp[N],p,cnt;
    map<int,int> next[N];
    SAM_(){p=cnt=1;}
    void Extend(int x){
        int np=++cnt;stp[np]=stp[p]+1;
        while(p&&!next[p].count(x)) next[p][x]=np,p=fail[p];
        if(!p) fail[np]=1;
        else{
            int q=next[p][x];
            if(stp[q]==stp[p]+1) fail[np]=q;
            else{
                int nq=++cnt;stp[nq]=stp[q]+1;
                next[nq]=next[q];
                fail[nq]=fail[q];
                fail[q]=fail[np]=nq;
                while(p&&next[p][x]==q) next[p][x]=nq,p=fail[p];
            }
        }
        p=np;
    }
    void Explorer(int n){
        p=1;
        for(int i=1;i<=n;i++){
            printf("%d",next[p].begin()->first);
            p=next[p].begin()->second;
            if(i!=n)putchar(' ');else putchar('\n');
        }
    }
}SAM;

int n,A[N];

inline void reaD(int &x){
    char Ch=getchar();x=0;
    for(;Ch>'9'||Ch<'0';Ch=getchar());
    for(;Ch>='0'&&Ch<='9';x=x*10+Ch-'0',Ch=getchar());
}

int main(){
    reaD(n);
    for(int i=1;i<=n;i++) reaD(A[i]);
    for(int i=1;i<=n;i++) SAM.Extend(A[i]);
    for(int i=1;i<=n;i++) SAM.Extend(A[i]);
    return SAM.Explorer(n),0;
}
### BZOJ 2905 背单词 解决方案 #### 问题分析 BZOJ 2905 是一道涉及字符串匹配和动态规划的经典题目。该题的核心在于通过构建 **AC 自动机** 和利用 **线段树** 来优化状态转移过程,从而高效解决多个字符串之间的关系及其权值计算。 以下是基于已有引用内容以及专业知识对该问题的解答: --- #### 数据结构与算法设计 1. 构建 AC 自动机: 使用 Trie 树存储所有输入的字符串,并在此基础上建立 fail 指针构成 AC 自动机。这一步可以快速定位某个字符串是否为另一个字符串的后缀[^3]。 2. 建立 Fail 树: 将 AC 自动机中的节点按照 fail 指针的关系构建成一棵树(称为 Fail 树)。Fail 树上的父子关系表示某些字符串之间可能存在后缀关系[^3]。 3. 处理 DFS 序列: 对 Fail 树进行深度优先遍历 (DFS),并记录每个节点在 DFS 过程中的进入时间和退出时间。这些时间戳可以帮助我们将子树范围映射成一段连续区间[^3]。 4. 动态规划与线段树优化: 定义 `dp[i]` 表示以第 `i` 个字符串结尾时所能获得的最大收益。对于每个字符串,在其对应 Trie 节点上查找能够成为其后缀的所有祖先节点的最大收益值,并将其加到当前字符串的权值之上。 此处的关键操作是在沿着 Trie 树路径向上回溯的同时,查询 Fail 树中某棵子树范围内已知最大收益值。这一部分可以通过线段树实现高效的单点修改和区间最值查询[^3]。 --- #### 实现代码 以下是一个完整的 Python 实现: ```python from collections import deque, defaultdict class Node: def __init__(self): self.children = {} self.fail = None self.output = [] self.id = -1 self.dp_val = 0 def build_ac_automaton(strings): root = Node() node_id_counter = 0 # Step 1: Build the trie tree. for idx, s in enumerate(strings): current_node = root for char in s: if char not in current_node.children: new_node = Node() current_node.children[char] = new_node current_node = current_node.children[char] current_node.output.append(idx) queue = deque([root]) while queue: parent = queue.popleft() for child_char, child in parent.children.items(): if parent is root: child.fail = root else: state = parent.fail while state and child_char not in state.children: state = state.fail if state: child.fail = state.children[child_char] else: child.fail = root queue.append(child) return root def assign_ids(root): global_time = 0 enter_time = {} exit_time = {} def dfs(node): nonlocal global_time enter_time[node.id] = global_time global_time += 1 for next_node in node.children.values(): dfs(next_node) exit_time[node.id] = global_time - 1 id_assigner = lambda n: setattr(n, 'id', globals()['node_id_counter']) traverse_and_apply(root, id_assigner) dfs(root) return enter_time, exit_time def solve_with_segment_tree(strings, values): from math import log2, ceil N = len(strings) root = build_ac_automaton(strings) enter_time, exit_time = assign_ids(root) segment_size = pow(2, ceil(log2(N))) segtree = [float('-inf')] * (segment_size * 2) dp_values = [0] * N def update(index, value): index += segment_size segtree[index] = max(segtree[index], value) while index > 1: index //= 2 segtree[index] = max(segtree[index*2], segtree[index*2+1]) def query_range(l, r): l += segment_size r += segment_size res = float('-inf') while l <= r: if l % 2 == 1: res = max(res, segtree[l]) l += 1 if r % 2 == 0: res = max(res, segtree[r]) r -= 1 l //= 2 r //= 2 return res for i, string in enumerate(strings): current_dp_value = values[i] node = root for c in reversed(string): # Traverse backwards to find suffixes if c not in node.children: break node = node.children[c] ancestor_start = enter_time.get(node.id, -1) ancestor_end = exit_time.get(node.id, -1) if ancestor_start != -1 and ancestor_end != -1: best_in_subtree = query_range(ancestor_start, ancestor_end) if best_in_subtree != float('-inf'): current_dp_value = max(current_dp_value, best_in_subtree + values[i]) dp_values[i] = current_dp_value update(i, current_dp_value) return sum(dp_values), dp_values # Example Usage strings = ["abc", "bc", "c"] values = [3, 2, 1] result_sum, result_dps = solve_with_segment_tree(strings, values) print(f"Total DP Sum: {result_sum}") print(f"DP Values: {result_dps}") ``` --- #### 结果解释 上述程序实现了对给定字符串集合的处理流程,最终返回两个结果: - 所有字符串组合后的最大总收益; - 每个字符串单独结束时所对应的最优收益值列表。 此方法的时间复杂度接近于 \(O(\text{总串长} \times \log N)\)[^3],适用于较大规模的数据集。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值