当前位置: 代码迷 >> 综合 >> 【HDU 1075 What Are You Talking About】 字典树(Trie树)
  详细解决方案

【HDU 1075 What Are You Talking About】 字典树(Trie树)

热度:91   发布时间:2023-12-29 02:52:17.0

HDU1075
本题的题意是给你火星文与地球文的映射方式,然后给你一个火星文组成的文本,若某单词在映射文本中出现过,则输出映射之后的文本。否则输出原文本。
我们可以建立trie树,插入火星文本,将返回的下标pos与地球文相对应,在翻译文本的时候,从前往后截取每一段单词,在trie树上查找该单词是否出过,要注意必须是单词,而不能是某单词的前缀。若找到则返回下标,然后输出该下标对应的地球文,否则返回-1,输出原文本。
HDU1075代码

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<iostream>
using namespace std;
const int maxn = 2e6+5;
int tree[maxn][30];
int flagg[maxn];
int pos[maxn];
int tot,tot2;
int insert_(char *str)
{int len=strlen(str);int root=0;for(int i=0;i<len;i++){int id=str[i]-'a';if(!tree[root][id]) tree[root][id]=++tot;root=tree[root][id];}flagg[root]=true;return root;//返回下标,对应的是一个单词
}
int find_(char *str)
{int root=0;int len=strlen(str);for(int i=0;i<len;i++){int id=str[i]-'a';if(!tree[root][id]) return -1;root=tree[root][id];}if(flagg[root]) return root;//若为完整相匹配单词,返回下标else return -1;
}
char ss1[maxn][12];
char tmp[maxn];
int main()
{int cnt=0;scanf("%s",tmp);while(scanf("%s",ss1[cnt])!=EOF){if(ss1[cnt][0]=='E'){scanf("%s",tmp);break;}scanf("%s",tmp);pos[insert_(tmp)]=cnt;//将返回的下标与地球文进行匹配cnt++;}getchar();while(gets(tmp)!=NULL){if(tmp[0]=='E') break;int len=strlen(tmp);char str[12];int cnt;for(int i=0;i<len;i++){if(tmp[i]>='a'&&tmp[i]<='z'&&i<len){cnt=0;while(tmp[i]>='a'&&tmp[i]<='z'){str[cnt++]=tmp[i++];}str[cnt]='\0';//截取单词,存在str中int pp=find_(str);if(pp!=-1)printf("%s",ss1[pos[find_(str)]]);//输出对应的地球文elseprintf("%s",str);printf("%c",tmp[i]);}elseprintf("%c",tmp[i]);}printf("\n");}return 0;
}