[bzoj3172][Tjoi2013]单词——AC自动机

本文介绍了一种使用AC自动机解决论文中单词频数统计问题的方法。通过构建失败指针,统计子树内节点权值和,实现高效单词频率计算。

题目大意:

某人读论文,一篇论文是由许多单词组成。但他发现一个单词会在论文中出现很多次,现在想知道每个单词分别在论文中出现多少次。

思路:

第i个单词在整个文章中出现了多少次即i串的结尾可以被多少个串的节点给跳到。
于是吧fail看成每个节点唯一的父亲,每个节点的权值为有多少个单词的前缀经过了它,然后直接统计子树内的权值和即可。

#include<bits/stdc++.h>

#define REP(i,a,b) for(int i=a,i##_end_=b;i<=i##_end_;++i)
#define DREP(i,a,b) for(int i=a,i##_end_=b;i>=i##_end_;--i)
#define debug(x) cout<<#x<<"="<<x<<" "
#define fi first
#define se second
#define mk make_pair
#define pb push_back
typedef long long ll;

using namespace std;

void File(){
    freopen("bzoj3172.in","r",stdin);
    freopen("bzoj3172.out","w",stdout);
}

template<typename T>void read(T &_){
    _=0; T f=1; char c=getchar();
    for(;!isdigit(c);c=getchar())if(c=='-')f=-1;
    for(;isdigit(c);c=getchar())_=(_<<1)+(_<<3)+(c^'0');
    _*=f;
}

const int maxn=1e6+10;
int n,cnt_rank,ans[maxn],weight[maxn];
int ch[maxn][26],num[maxn],fail[maxn],cnt=1;
vector<int>rank[maxn];

void insert(char *s){
    int len=strlen(s+1),u=1,c;
    REP(i,1,len){
        c=s[i]-'a';
        if(!ch[u][c])ch[u][c]=++cnt;
        u=ch[u][c];
        ++weight[u];
    }
    ++num[u];
    rank[u].pb(++cnt_rank);
}

void build_fail(){
    int h=1,t=0,q[maxn];
    fail[1]=1;
    REP(i,0,25){
        int v=ch[1][i];
        if(v)q[++t]=v;
        if(v)fail[v]=1;
        else ch[1][i]=1;
    }
    while(h<=t){
        int u=q[h++];
        REP(i,0,25){
            int v=ch[u][i];
            if(v)q[++t]=v;
            if(v)fail[v]=max(ch[fail[u]][i],1);
            else ch[u][i]=max(ch[fail[u]][i],1);
        }
    }
}

int beg[maxn],to[maxn],las[maxn],cnte=1;
int sz[maxn];

void add(int u,int v){
    las[++cnte]=beg[u]; beg[u]=cnte; to[cnte]=v;
}

void dfs(int u){
    sz[u]=weight[u];
    for(int i=beg[u];i;i=las[i]){
        dfs(to[i]);
        sz[u]+=sz[to[i]];
    }
    REP(i,0,rank[u].size()-1)ans[rank[u][i]]=sz[u];
}

int main(){
    File();

    char s[maxn];

    read(n);
    REP(i,1,n){
        scanf("%s",s+1);
        //printf("%s\n",s+1);
        insert(s);
    }

    build_fail();
    REP(i,2,cnt)add(fail[i],i);

    dfs(1);

    REP(i,1,n)printf("%d\n",ans[i]);

    return 0;
}

转载于:https://www.cnblogs.com/ylsoi/p/10185297.html

### 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],适用于较大规模的数据集。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值