标签:php syn problem only ext ast mes others follow
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 70290 Accepted Submission(s): 23917
题意:给出一个字典和一个模式串,问模式串中出现几个字典中的单词
代码:
1 ////#include "bits/stdc++.h" 2 #include "cstdio" 3 #include "map" 4 #include "set" 5 #include "cmath" 6 #include "queue" 7 #include "vector" 8 #include "string" 9 #include "cstring" 10 #include "time.h" 11 #include "iostream" 12 #include "stdlib.h" 13 #include "algorithm" 14 #define db double 15 #define ll long long 16 //#define vec vector<ll> 17 #define Mt vector<vec> 18 #define ci(x) scanf("%d",&x) 19 #define cd(x) scanf("%lf",&x) 20 #define cl(x) scanf("%lld",&x) 21 #define pi(x) printf("%d\n",x) 22 #define pd(x) printf("%f\n",x) 23 #define pl(x) printf("%lld\n",x) 24 #define rep(i, x, y) for(int i=x;i<=y;i++) 25 const int N = 1e6 + 5; 26 const int mod = 1e9 + 7; 27 const int MOD = mod - 1; 28 const db eps = 1e-18; 29 const db PI = acos(-1.0); 30 using namespace std; 31 const int M = 26; 32 queue<int> q; 33 vector<string> vec; 34 bool vis[N]; 35 struct Trie { 36 int trieN; 37 int ch[N][M], val[N], fail[N]; 38 void init() { 39 memset(vis,0,sizeof(vis)); 40 trieN = -1; 41 newnode(); 42 } 43 int newnode() { 44 memset(ch[++trieN], 0, sizeof(ch[0])); 45 val[trieN] = fail[trieN] = 0; 46 return trieN; 47 } 48 void insert(const string &str, int index) { 49 int cur = 0; 50 for (int i = 0;str[i];i++) { 51 int d = str[i] - ‘a‘; 52 if (!ch[cur][d]) 53 ch[cur][d] = newnode(); 54 cur = ch[cur][d]; 55 } 56 if (val[cur]) vis[index] = 1; 57 else val[cur] = index; 58 } 59 void build() { 60 for (int i = 0;i < M;i++) { 61 if (ch[0][i]) 62 q.push(ch[0][i]); 63 } 64 while (!q.empty()) { 65 int cur = q.front(); q.pop(); 66 for (int i = 0;i < M;i++) { 67 int &next = ch[cur][i]; 68 if (next) { 69 fail[next] = ch[fail[cur]][i]; 70 q.push(next); 71 } 72 else next = ch[fail[cur]][i]; 73 } 74 } 75 } 76 void query(const string &str) { 77 int cur = 0, tmp; 78 for (int i = 0;str[i];i++) { 79 int d = str[i] - ‘a‘; 80 tmp = cur = ch[cur][d]; 81 while (tmp && ~val[tmp]) { 82 if (val[tmp] != -1) vis[val[tmp]] = 1; 83 val[tmp] = -1; 84 tmp = fail[tmp]; 85 } 86 } 87 } 88 }ac; 89 90 int main(){ 91 ios::sync_with_stdio(false); 92 cin.tie(0); 93 int t; 94 cin >> t; 95 while(t--){ 96 ac.init(); //初始化 97 int n; 98 string str; 99 cin >> n; 100 vec.resize(n+1); 101 for(int i = 1;i <= n;i++){ 102 cin >> vec[i]; 103 ac.insert(vec[i],i); 104 } 105 ac.build(); 106 cin>>str; 107 ac.query(str); //查询是否在str里出现过 108 int ans=0; 109 for(int i = 1;i <= n;i++){ 110 if (vis[i]) ans++; 111 } 112 pi(ans); 113 } 114 return 0; 115 }
标签:php syn problem only ext ast mes others follow
原文地址:http://www.cnblogs.com/mj-liylho/p/8010639.html