标签:
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 102400/204800 K (Java/Others)
Total Submission(s): 20680 Accepted Submission(s): 6852
题目链接:HDU 1075
结构体Trie中用flag=1表示当前点是否是某个单词的结尾处(防止出现单词a为单词b的前缀但是却被b覆盖的情况,比如diff对应bbb,但是此时diff的前缀dif显然是不存在的),若为结尾,则flag赋值为1,然后把对应的翻译单词赋值给这个节点的s[]。
查询的是否看查完之后的flag是否为1,如果为1则存在该单词,否则flag为0或根本查不到,则返回NULL
一开始智障了把每个点flag都设为1狂WA……
代码:
#include <stdio.h> #include <iostream> #include <algorithm> #include <cstdlib> #include <sstream> #include <cstring> #include <bitset> #include <string> #include <deque> #include <stack> #include <cmath> #include <queue> #include <set> #include <map> using namespace std; #define INF 0x3f3f3f3f #define CLR(x,y) memset(x,y,sizeof(x)) #define LC(x) (x<<1) #define RC(x) ((x<<1)+1) #define MID(x,y) ((x+y)>>1) typedef pair<int,int> pii; typedef long long LL; const double PI=acos(-1.0); const int N=26; const int M=100; struct Trie { Trie *nxt[N]; int flag; char s[M]; Trie() { CLR(nxt,0); CLR(s,0); flag=0; } }; Trie *L=new Trie(); void update(char s[],char earth[]) { int len=strlen(s); int indx; Trie *cur=L; for (int i=0; i<len; ++i) { indx=s[i]-‘a‘; if(cur->nxt[indx]) cur=cur->nxt[indx]; else { Trie *one=new Trie(); cur->nxt[indx]=one; cur=one; } } strcpy(cur->s,earth); cur->flag=1; } char* Find(char s[]) { int len=strlen(s); int indx; Trie *cur=L; for (int i=0; i<len; ++i) { indx=s[i]-‘a‘; if(cur->nxt[indx]==NULL) return NULL; cur=cur->nxt[indx]; } return cur->flag?cur->s:NULL; } char from[M],to[M]; char tot[1000010]; char temp[M]; int main(void) { int i; scanf("%s",from); getchar(); while (~scanf("%s",to)&&strcmp(to,"END")) { scanf("%s",from); update(from,to); } getchar(); gets(from); while (gets(tot)&&strcmp(tot,"END")) { int len=strlen(tot); int k=0; CLR(temp,0); for (i=0; i<len; ++i) { if(islower(tot[i])) temp[k++]=tot[i]; else { char *one=Find(temp); if(k) printf("%s",one==NULL?temp:one); putchar(tot[i]); CLR(temp,0); k=0; } } if(k) { char *one=Find(temp); printf("%s",one==NULL?temp:one); } putchar(‘\n‘); } return 0; }
HDU 1075 What Are You Talking About(Trie的应用)
标签:
原文地址:http://www.cnblogs.com/Blackops/p/5908836.html