第一道trie

还需要写题来建立自己的代码习惯。

 #include <cstdio>
#include <vector>
#include <algorithm>
#define maxn 20010
using namespace std; struct node {
char v;
int sz;
bool isword, mark;
node *son[], *pre;
}pool[maxn], *tail=pool, *null=pool; char temp[];
struct Trie {
node *root;
vector<node*> stk;
node* newnode( node *p, char v ) {
node *nd = ++tail;
nd->sz = ;
nd->v = v;
nd->isword = nd->mark = false;
nd->pre = p;
for( int i=; i<; i++ ) nd->son[i] = null;
return nd;
}
void insert( const char *str ) {
if( !root ) root=newnode(null,'^');
node *nd=root;
while() {
if( *str ) {
if( nd->son[*str-'a']==null ) nd->son[*str-'a']=newnode(nd,*str-'a');
nd->sz++;
nd = nd->son[*str-'a'];
str++;
} else {
nd->isword = true;
stk.push_back( nd );
return;
}
}
}
void make_mark( node *nd ) {
if( nd->isword ) {
nd->mark = true;
for( int i=; i<; i++ )
if( nd->son[i]!=null ) make_mark(nd->son[i]);
} else if( nd->sz== ) {
nd->mark = true;
} else {
for( int i=; i<; i++ )
if( nd->son[i]!=null ) make_mark(nd->son[i]);
}
}
char *get( node *bt ) {
while( !bt->mark ) bt=bt->pre;
int i;
for( i=; bt!=root; i++,bt=bt->pre )
temp[i] = bt->v+'a';
temp[i] = ;
reverse( temp, temp+i );
return temp;
}
void print( node *nd ) {
fprintf( stderr, "nd %d ch %c mark %d\n", nd-pool, nd->v+'a', nd->mark );
for( int i=; i<; i++ )
if( nd->son[i]!=null ) print(nd->son[i]);
}
}T; void pt( char *st ) {
fprintf( stderr, "%s\n", st );
}
char str[][];
int main() {
int i;
for( i=; ; i++ ) {
if( scanf( "%s", str[i] )!= ) {
i--;
break;
}
T.insert( str[i] );
}
for( int i=; i<; i++ )
if( T.root->son[i]!=null )
T.make_mark( T.root->son[i] );
for( int t=; t<=i; t++ )
printf( "%s %s\n", str[t], T.get(T.stk[t]) );
}

最新文章

  1. 18.tty驱动程序框架
  2. php代码美化/格式化 还原 -问题
  3. HDU 2577(DP)
  4. C++学习之静态成员
  5. jsoncpp用法通俗易懂之解析
  6. 第二十二章 数据访问(In .net4.5) 之 集合
  7. 设置VMWARE通过桥接方式使用主机无线网卡上网
  8. HDU5777 domino (BestCoder Round #85 B) 思路题+排序
  9. WPF中如何使用图像API进行绘制
  10. zookeeper选举代码分析
  11. c++面试(二)
  12. Android_通过ContentObserver监听短信数据变化
  13. 依赖注入(DI)和控制反转(IOC)【回顾】
  14. ImageLoader的使用
  15. [Open Source] 负载均衡之Nginx
  16. h5audio标签
  17. Docker 中国官方镜像加速
  18. jQuery的学习笔记4
  19. Scrapy 1.4 文档 02 安装指南
  20. JavaScript模块化CommonJS/AMD/CMD/UMD/ES6Module的区别

热门文章

  1. TensorFlow下利用MNIST训练模型识别手写数字
  2. python3学习笔记.1.初体验
  3. layui的模块化和非模块化使用
  4. (3)剑指Offer之数值的整数次方和调整数组元素顺序
  5. nvidia tx1使用记录--基本环境搭建
  6. LFM隐语义模型Latent Factor Model
  7. 主机名/etc/hosts文件的作用
  8. ie6下png图片背景色处理
  9. Jury Jeopardy(反向模拟)
  10. &lt;&lt;Javascript Patterns&gt;&gt;阅读笔记 – 第3章 字面量和构造函数