首页 技术 正文
技术 2022年11月18日
0 收藏 981 点赞 3,434 浏览 1291 个字

中文题题意不再赘述

注意 失配数组 f  初始化一步到位

#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;#define N 2000100
#define maxnode 50010
#define sigma_size 26
struct node{
char name[55];
int num;
}S[1101];
struct Trie{
int ch[maxnode][sigma_size];
int val[maxnode];
int f[maxnode];
int sz;
void init(){
sz=1;
memset(ch,0,sizeof(ch));
memset(val,0,sizeof(val));
memset(f,0,sizeof(f));
val[0] = 0;
}
int idx(char c){
return c-'A';
}void Creat(char *s, int num){
int u = 0, len = strlen(s);
for(int i = 0; i < len; i++){
int c = idx(s[i]);
if(!ch[u][c]) ch[u][c] = sz++;
u = ch[u][c];
}
val[u] = num ; //u若是单词结尾则为 +1
} int find(char *T){
int len = strlen(T);
int j = 0;
for(int i = 0; i < len; i++){
if(T[i]<'A' || T[i]>'Z'){ j = 0; continue;}
int c = idx(T[i]);
j = ch[j][c];
int temp = j;
while(temp && val[temp]){
S[ val[temp] ].num ++;
temp = f[ temp ];
}
}return 0;
}void getFail(){
queue<int> q;
//初始化队列
for(int c = 0; c < sigma_size; c++)
if(ch[0][c])q.push(ch[0][c]);while(!q.empty()){
int r = q.front(); q.pop();
for(int c = 0; c < sigma_size; c++){
int u = ch[r][c];
if(!u){ ch[r][c] = ch[f[r]][c]; continue; }
q.push(u);
int v = f[r];
while(v && !ch[v][c]) v = f[v]; //沿失配边追溯到可以匹配的(非原点)位置
f[u] = ch[v][c];
}
}
}
};
Trie ac;
char S1[N];int main(){
int n;
while(~scanf("%d",&n)){
ac.init();
for(int i = 1; i <= n; i++){
scanf("%s",S[i].name);
S[i].num = 0;
ac.Creat(S[i].name, i);
}
ac.getFail();scanf("%s",S1);
ac.find(S1);for(int i = 1; i <= n; i++)
if(S[i].num)
printf("%s: %d\n",S[i].name, S[i].num);}
return 0;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,000
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,512
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,358
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,141
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,771
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,849