本文共 2212 字,大约阅读时间需要 7 分钟。
今天刚刚把Trie图的模板弄到了,并且解决一个简单的多模匹配的问题HDU2222,想到上次做福州赛区的那道题,今天就套模板做了一下,很快乐地就AC了! 呵呵……其实也没那么顺利!
第一次提交超空间了!主要是我傻呼呼的把子串反过来插入Trie图中,后来看书上,原来是把母串反转,然后再查一次就OK了!
第二次提交果断WA了,后来打印解压的结果才发现,自己忘记了把解压缩的母串末尾加上结束符 s[end]='\0';
第三次提交果断AC了!不管怎么样,感觉挺爽的 呵呵!
把代码贴上来吧!
-
-
-
-
- #include<stdio.h>
- #include<string.h>
- #include<queue>
- using namespace std;
- #define M 6000000
- char word[1105];
- char ds[M];
- char s[M];
- char rs[M];
- struct Node{
- int tail;
- Node *prefix;
- Node *next[26];
- Node(){
- memset(next,0,sizeof(next));
- tail=0;
- }
- }*root;
- void init(){
- root=new Node();
- }
- void insert(char *word){
- Node *p=root;
- int idx;
- while(*word){
- idx=*word-'A';
- if(p->next[idx]==0){
- p->next[idx]=new Node();
- }
- p=p->next[idx];
- word++;
- }
- p->tail++;
- }
- void add_prefix(){
- root->prefix = NULL;
- deque<Node* > q;
- q.push_back(root);
-
- while(!q.empty()) {
- Node* tmp = q.front();
- Node* p = NULL;
- q.pop_front();
- for(int i = 0; i < 26; ++i) {
- if(tmp->next[i] != NULL) {
- if(tmp == root) tmp->next[i]->prefix = root;
- else {
- p = tmp->prefix;
- while(p != NULL) {
- if(p->next[i] != NULL) {
- tmp->next[i]->prefix = p->next[i];
- break;
- }
- p = p->prefix;
- }
- if(p == NULL) tmp->next[i]->prefix = root;
- }
- q.push_back(tmp->next[i]);
- }
- }
- }
- }
- void reverse(char *s){
- int len=strlen(s);
- int i,j;
- for(i=len-1,j=0;i>=0;i--){
- rs[j++]=s[i];
- }
- rs[j]=0;
-
- }
- int search(char *st){
- int cnt = 0, t;
- Node* p = root;
- while(*st) {
- t = *st - 'A';
- while(p->next[t] == NULL && p != root) {
- p = p->prefix;
- }
- p = p->next[t];
- if(p == NULL) p = root;
-
- Node* tmp = p;
- while(tmp != root && tmp->tail != -1) {
- cnt += tmp->tail;
- tmp->tail = -1;
- tmp = tmp->prefix;
- }
- st++;
- }
- return cnt;
- }
-
- void decode(){
- int len_ds=strlen(ds);
- int i,j,k,len;
- i=j=0;
- while(i<len_ds){
- if(ds[i]>='A'&&ds[i]<='Z'){
- s[j++]=ds[i];
- }else if(ds[i]=='['){
- i++;
- len=0;
- while(ds[i]>='0'&&ds[i]<='9'){
- len=len*10+(ds[i]-'0');
- i++;
- }
- for(k=0;k<len;k++){
- s[j++]=ds[i];
- }
- i++;
- }
- i++;
- }
- s[j]=0;
-
- }
- int main(){
- int t,n,i;
- scanf("%d",&t);
- while(t--){
- init();
- scanf("%d",&n);
- for(i=0;i<n;i++){
- scanf("%s",word);
- insert(word);
- }
- add_prefix();
- scanf("%s",ds);
- decode();reverse(s);
- printf("%d\n",search(s)+search(rs));
- }
- }
转载地址:http://sfadx.baihongyu.com/