POJ 2001 Shortest Prefixes(字典树)
来源:互联网 发布:梦幻西游mac版字体小 编辑:程序博客网 时间:2024/03/29 20:17
题目链接:Shortest Prefixes
题意:n个字符串,求每个字符串的最短非公共前缀,若没有输出其本身
思路:利用字典树记录每个前缀使用的次数,以前标记作用的flag当做计数功能,所以使用次数非1的肯定是与其他字符串存在前缀,从首字母到第一非1的字符就是最短非公共前缀;
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>const int N = 20010;using namespace std;struct node{ int flag; node *next[26];};int n,m;struct node *make(){ node *root = new node; for(int i = 0;i<26;i++) root->next[i] = NULL; root->flag = 1; return root;}struct node *creat(){ node *p = new node; for(int i = 0;i<26;i++) p->next[i] = NULL; p->flag = 0; return p;}void Insert(struct node *p,char *a){ int len = strlen(a); int num; node *q; for(int i = 0;i<len;i++) { num = a[i]-'a'; if(p->next[num]==NULL) { //q=(struct node *)calloc(1,sizeof(struct node)); q = creat(); p->next[num] = q; p = q; p->flag = 1; } else { p = p->next[num]; p->flag++; } // printf("%d %c |", p->flag, a[i]); } // p->flag++;}void Search(struct node *p,char *a){ int len = strlen(a); for(int i = 0;i<len;i++) {// int num = a[i]-'a';// char c = 'a' + num;// putchar(c);// if(p->flag==1)// break;// else// p= p->next[num]; int num=a[i]-'a'; p=p->next[num]; printf("%c", a[i]); if(p->flag==1) break; }}/*void Search(struct node *p,char *a){ int len = strlen(a); for(int i = 0;i<len;i++) { int num = a[i]-'a'; char c = 'a' + num; putchar(c); if(p->flag==1) break; p= p->next[num]; }}*/void FREE(struct node *root){ if(root==NULL)return; for(int i = 0;i<26;i++) { if(root->next[i]!=NULL) FREE(root->next[i]); } free(root); root = NULL;}int main(){ char a[1010][30]; node *root; root = make(); n=0; while(~scanf("%s",a[n])) { //node *root = new node; Insert(root,a[n]); // printf("\n"); n++; } for(int i = 0;i<n;i++) { printf("%s ",a[i]); Search(root,a[i]); cout<<endl; } FREE(root); //system("pause"); return 0;}
0 0
- POJ 2001:Shortest Prefixes(字典树)
- poj 2001 -- Shortest Prefixes ( 字典树 )
- POJ 2001-Shortest Prefixes(字典树)
- POJ 2001 Shortest Prefixes(字典树)
- POJ 2001 Shortest Prefixes(字典树)
- poj 2001 Shortest Prefixes(字典树)
- POJ - 2001 - Shortest Prefixes (字典树!!)
- POJ 2001 Shortest Prefixes(字典树)
- POJ 2001 Shortest Prefixes(字典树)
- POJ 2001 Shortest Prefixes(字典树)
- POJ 2001 Shortest Prefixes(字典树)
- 【POJ】2001 - Shortest Prefixes(字典树)
- POJ 2001 Shortest Prefixes(字典树)
- poj 2001 Shortest Prefixes(字典树)
- poj 2001Shortest Prefixes(字典树)
- poj 2001 Shortest Prefixes(字典树)
- POJ 2001 Shortest Prefixes ( 字典树 )
- POJ 2001 Shortest Prefixes 字典树Trie
- 总结几个 C 语言知识点
- 排名前五位的Java网站,让猫抗击
- pdf转换器绿色版下载
- struts2 Interceptor怎么写
- 解决crontab无法读取环境变量
- POJ 2001 Shortest Prefixes(字典树)
- Linux DebugFS 子目录也是用debugfs_create_dir来实现
- java进制转换
- Java - 编译器的贪心规则
- 经纬财富:巢湖头肩顶形态如何交易
- Unexpected text found in layout file: """
- 智力测试---20140731
- HDU 1969 Pie(二分查找)
- SharePoint 2013 托管导航及相关配置