UVAlive - 5792 Diccionário Portuñol (Trie)
来源:互联网 发布:sql修改约束条件 编辑:程序博客网 时间:2024/05/16 06:18
转自:cxlove
题意:有两个字符串集合,从第一个集合中取某个串的非空前缀,从第二个集合中取某个串的非空后缀,拼接成一个串,问有多少个不同的新串。
思路:首先把第一个集合中的串加入到Trie中,然后就可以枚举前缀了,然后就是统计后缀,麻烦的是可能出现重复的。
当我们按长度枚举前缀的时候,可以考虑如果后缀的前缀出现在前缀的后继中,那便不用考虑,后面总会统计到。
这样的话,其实只要比较第一个字母。
如果当前结点P表示一个前缀串,那么如果p -> next[i]为空,说明前缀中不含字母i为后继,那么我们就可以统计以i开头的后缀了。否则总能在p -> next[i]为前缀中统计到。
有一点需要注意的是,如果 p -> next[i]便是我们最终的串,即以p 为前缀时,后缀只有一个字母的话,那就不能把这一个字母拉入到前缀中,因为后缀是非空的。所以再处理下end[i],表示是否存在以单个字母i为后缀的。
至于统计以i开头的不重复后缀的话,可以反向加入到Trie中统计。
#include<iostream>#include<cstdio>#include<string>#include<cstring>#include<vector>#include<cmath>#include<queue>#include<stack>#include<map>#include<set>#include<algorithm>using namespace std;typedef long long LL;const int maxn=100010;const int maxm=1010;const int SIGMA_SIZE=26;int P,S;char a[maxm][maxm],b[maxm][maxm];int tail[maxn];int cnt[30];LL ans;struct Trie{ int ch[maxn][SIGMA_SIZE]; int val[maxn]; int sz; void clear(){memset(ch[0],0,sizeof(ch[0]));sz=1;} int idx(char x){return x-'a';} void insert(char *s) { int u=0; for(int i=0;s[i];i++) { int c=idx(s[i]); if(!ch[u][c]) { memset(ch[sz],0,sizeof(ch[sz])); val[sz]=0; ch[u][c]=sz++; } u=ch[u][c]; } val[u]=1; } void cal(int u) { for(int i=0;i<SIGMA_SIZE;i++) { if(ch[u][i]) { cnt[i]++; cal(ch[u][i]); } } } void solve(int u) { for(int i=0;i<SIGMA_SIZE;i++) { if(!ch[u][i]) { if(u) ans+=cnt[i]; } else { if(u&&tail[i])ans++; solve(ch[u][i]); } } }}prefix,suffix;int main(){ while(scanf("%d%d",&P,&S)!=EOF,P||S) { prefix.clear(); suffix.clear(); memset(cnt,0,sizeof(cnt)); memset(tail,0,sizeof(tail)); for(int i=0;i<P;i++) { scanf("%s",a[i]); prefix.insert(a[i]); } for(int i=0;i<S;i++) { scanf("%s",b[i]); reverse(b[i],b[i]+strlen(b[i])); tail[b[i][0]-'a']=1; suffix.insert(b[i]); } ans=0; suffix.cal(0); prefix.solve(0); cout<<ans<<endl; } return 0;}
0 0
- UVAlive 5792 Diccionário Portuñol (Trie)
- UVAlive - 5792 Diccionário Portuñol (Trie)
- UVALive 5792 Diccionário Portuñol(字典树)
- UVAlive5792 Diccionário Portuñol
- BNU 12674 Diccionário Portuñol (字典树统计)
- UVALIVE 5792 Trie+统计
- rio
- uvalive 3942(dp + trie)
- uvalive 7043(trie)
- UVALive 3942 Trie加速dp
- UVALive 5913 Dictionary Size (Trie)
- ol
- ol
- UVALive - 3942 Remember the Word (Trie)
- UVALive (LA) - 3942 UVa 1401 Trie
- uvalive 3942 - Remember the Word(Trie)
- Cellphone Typing - UVaLive 6133 Trie树
- UVALive - 3942 Remember the Word Trie
- 简历就该简而有力!
- Windows命令行
- java反射机制实例解析
- arm-none-eabi-gcc编译器的安装和相关配置
- Eclipse离线安装SVN插件速度很慢的解决办法
- UVAlive - 5792 Diccionário Portuñol (Trie)
- stub 和 skeleton 的讲解,自己实现一个stub和skeleton程序
- android Tabhost部件(三)--使用自定义view和fragement实现类似TabHost样式
- C++的精髓——虚函数
- 数组里a和&a的区别
- [HttpException (0x80004005): 未能加载文件或程序集“Oracle.DataAccess”或它的某一个依赖项。试图加载格式不正确的程序。]
- CGRectInset CGRectoffset UIEdgeInsetsInsetRect 这三个函数的使用
- stripslashes和addslashes的区别
- Android官方培训课程中文版