标签:
题目链接:传送门
题目大意:中文题(大意略)
题目思路:tire入门题
用数组代替指针模拟字典树(代码易写,速度快)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cmath> 5 #include <algorithm> 6 #include <cstring> 7 #include <stack> 8 #include <cctype> 9 #include <queue> 10 #include <string> 11 #include <vector> 12 #include <set> 13 #include <map> 14 #include <climits> 15 #define lson root<<1,l,mid 16 #define rson root<<1|1,mid+1,r 17 #define fi first 18 #define se second 19 #define ping(x,y) ((x-y)*(x-y)) 20 #define mst(x,y) memset(x,y,sizeof(x)) 21 #define mcp(x,y) memcpy(x,y,sizeof(y)) 22 using namespace std; 23 #define gamma 0.5772156649015328606065120 24 #define MOD 1000000007 25 #define inf 0x3f3f3f3f 26 #define N 50005 27 #define maxn 400005 28 typedef pair<int,int> PII; 29 char s[111]; 30 struct Trie{ 31 int ch[maxn][26],alloc; ///alloc是节点变量,为节点之间建立联系 32 int val[maxn],cur; ///cur是当前正在访问的节点 33 int i,len; 34 void clc(){ ///字典树初始化操作 35 cur=0; 36 alloc=1; 37 mst(val,0); 38 mst(ch,-1); 39 } 40 void add(){ ///扩充节点(向树里增加新节点) 41 for(;i<len;++i){ 42 ch[cur][s[i]-‘a‘]=alloc++; 43 cur=ch[cur][s[i]-‘a‘]; 44 ++val[cur]; 45 } 46 } 47 void ins(){ ///扩充节点的值(扩充已有节点的值) 48 len=strlen(s); 49 cur=0; 50 for(i=0;i<len;++i){ 51 if(ch[cur][s[i]-‘a‘]==-1) add(); 52 else{ 53 cur=ch[cur][s[i]-‘a‘]; 54 ++val[cur]; 55 } 56 } 57 } 58 int query(){ ///询问 59 len=strlen(s); 60 cur=0; 61 for(i=0;i<len;++i){ 62 if(ch[cur][s[i]-‘a‘]==-1)return 0; 63 cur=ch[cur][s[i]-‘a‘]; 64 } 65 return val[cur]; 66 } 67 }trie; 68 69 int main(){ 70 int i,j,group; 71 trie.clc(); 72 //freopen("in.txt","r",stdin); 73 while(gets(s)&&strlen(s)) 74 trie.ins(); 75 while(gets(s)&&strlen(s)){ 76 printf("%d\n",trie.query()); 77 } 78 return 0; 79 }
标签:
原文地址:http://www.cnblogs.com/Kurokey/p/5576687.html