hdu 5384 Danganronpa

链接:http://acm.hdu.edu.cn/showproblem.php?pid=5384

思路:没学自动机时以为是道KMP然后就tle了好几把,AC自动机模板题

  1 #include<cstdio>  
  2 #include<iostream>  
  3 #include<algorithm>
  4 #include<math.h> 
  5 #include<string.h>  
  6 #include<vector> 
  7 #include<queue>
  8 #include<iterator>
  9 #include<vector>
 10 #include<set>
 11 #define dinf 0x3f3f3f3f
 12 #define LL long long
 13 using namespace std;
 14 const int N=100010;
 15 
 16 int n, m;
 17 string str[N];
 18 char s[N];
 19 
 20 struct node
 21 {
 22     int num;    //以本节点结尾的单词个数
 23     node *child[26];  //孩子
 24 } pos[N*50];
 25 node *tree_gen;
 26 
 27 int node_cnt;
 28 node * create_node()
 29 {
 30     pos[node_cnt].num=0;
 31     for(int i=0; i<26; i++) 
 32         pos[node_cnt].child[i]=0;
 33     return &pos[node_cnt++];
 34 }
 35 
 36 void insert_tree(char *p)
 37 {
 38     node *node_p=tree_gen;  //指向树根
 39     while(*p!='')
 40     {
 41         if( node_p->child[*p-'a']==0 )  //还没有这叉,就要建
 42         {
 43             node *new_node=create_node();   //创建新节点
 44             node_p->child[*p-'a']=new_node; //连接
 45             node_p=new_node;
 46         }
 47         else                        //已有这叉,继续往下
 48             node_p=node_p->child[*p-'a'];
 49         if( *(p+1)=='' )        
 50             node_p->num++;      //以此单词为结尾的
 51         p++;
 52     }
 53 }
 54 
 55 int query(string t)
 56 {
 57     int ans=0;
 58     node *node_p=tree_gen;  //指向树根
 59     int r=0;
 60     while( node_p!=0 && r<t.size() )
 61     {
 62         if(node_p->child[ t[r]-'a' ])
 63             node_p=node_p->child[ t[r]-'a' ];
 64         else break;
 65         r++;
 66         ans+=node_p->num;
 67     }
 68     return ans;
 69 }
 70 
 71 int cal(string &t)
 72 {
 73     int ans=0;
 74     for(int i=0; i<t.size(); i++)
 75         ans+=query(t.substr(i));
 76     return ans;
 77 }
 78 
 79 
 80 int main()
 81 {
 82     int t;
 83     cin>>t;
 84     while(t--)
 85     {
 86         scanf("%d%d", &n, &m);
 87         node_cnt=0;
 88         tree_gen=create_node();
 89 
 90         for(int i=0; i<n; i++)
 91             cin>>str[i];
 92         for(int i=0; i<m; i++)
 93         {
 94             scanf("%s",s);
 95             insert_tree(s);
 96         }
 97         for(int i=0; i<n; i++)
 98             printf("%d
", cal(str[i]));
 99     }
100     return 0;
101 }
原文地址:https://www.cnblogs.com/pter/p/5765633.html