题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1075 ,字典树的字符串映射。
题意是给你每个火星文单词对应的英语,然后让你把一篇火星文文章给翻译成英语。
解法:
在Trie树的每个结束标志处加一个字符串,这样就可以对每个火星文单词构造映射。构造映射后就可以处理翻译部分,可以用gets读入一行,然后对这一行进行处理,注意标点符号的情况。最后还有注意数组开大点。
#include <iostream> #include <cstdio> #include <vector> #include <queue> #include <stack> #include <cmath> #include <string> #include <string.h> #include <algorithm> using namespace std; #define LL __int64 const int maxn = 500000 + 5; const int sigma_size = 26; struct Trie { int ch[maxn][sigma_size]; char str[maxn][15]; bool isEnd[maxn]; int size; void init() { size = 1; memset(ch[0] , 0 , sizeof(ch[0])); memset(isEnd , 0 , sizeof(isEnd)); } int index(char c) { return c - ‘a‘; } void insert(char *s , char *s0) { int i , rt; for(i = rt = 0 ; s[i] != ‘\0‘ ; i++) { int c = index(s[i]); if(!ch[rt][c]) { memset(ch[size] , 0 , sizeof(ch[size])); ch[rt][c] = size++; } rt = ch[rt][c]; } strcpy(str[rt] , s0); isEnd[rt] = 1; } char *find(char *s) { int i , rt; for(i = rt = 0 ; s[i] != ‘\0‘ ; i++) { int c = index(s[i]); if(!ch[rt][c]) return "0"; rt = ch[rt][c]; } return (isEnd[rt]) ? str[rt] : "0"; } } trie; char s1[maxn] , s2[maxn]; int main() { trie.init(); while(~scanf("%s" , s1)) { if(!strcmp(s1 , "START")) continue; if(!strcmp(s1 , "END")) break; scanf("%s" , s2); trie.insert(s2 , s1); } getchar(); while(gets(s1)) { if(!strcmp(s1 , "START")) continue; if(!strcmp(s1 , "END")) break; int i = 0; while(s1[i] != ‘\0‘) { if(s1[i] >= ‘a‘ && s1[i] <= ‘z‘) { int j = 0; while(s1[i] != ‘\0‘ && s1[i] >= ‘a‘ && s1[i] <= ‘z‘) { s2[j++] = s1[i++]; } s2[j] = ‘\0‘; char *tmp = trie.find(s2); if(tmp[0] == ‘0‘) printf("%s" , s2); else printf("%s" , tmp); } else { putchar(s1[i++]); } } puts(""); } return 0; }
时间: 2024-12-07 15:40:59