标签:
1 4 preview predict premier press 3 pre press pree
4 1 0
用来练一下字典树模板,当年用快排+二分做的也很开心
#include<bits/stdc++.h> using namespace std; #define ll long long typedef struct node { int num; node *next[30]; node() { memset(next, 0, sizeof(next)); num = 0; } }Trie; char op[32], s[32]; void Insert(node *root, char *s) { node *p = root; for(int i = 0; s[i]; i++) { int x = s[i] - ‘a‘; if(p -> next[x] == NULL) p -> next[x] = new node; p = p -> next[x]; p -> num++; } } int Search(node *root, char *s) { node *p = root; for(int i = 0; s[i]; i++) { int x = s[i] - ‘a‘; if(p -> next[x] == NULL) return 0; p = p -> next[x]; } return p -> num; } void Delete(node *root, char *s, int cnt) { node *p = root; for(int i = 0; s[i]; i++) { int x = s[i] - ‘a‘; p = p -> next[x]; p -> num -= cnt; } for(int i = 0; i < 30; i++) p -> next[i] = 0; } int main() { int t; scanf("%d", &t); while(t--) { Trie *root = new node; int n; scanf("%d", &n); for(int i = 1; i <= n; i++) { scanf("%s", s); Insert(root, s); } scanf("%d", &n); for(int i = 1; i <= n; i++) { scanf("%s", s); printf("%d\n", Search(root, s)); } } }
#include<bits/stdc++.h> using namespace std; string ch[11111]; string pre[11111]; int cnt=0; void jiancha_right(int val2,string pr2) { if(val2 >= 0 && ch[val2].compare(0, pr2.size(), pr2) == 0) { cnt++; jiancha_right(val2+1,pr2); } else return; } void jiancha_left(int val2,string pr2) { if(val2 >= 0 && ch[val2].compare(0, pr2.size(), pr2) == 0) { cnt++; jiancha_left(val2-1,pr2); } else return; } int bbsearch(string pr,int m1,int n1) { int val; while(m1<n1) { val=m1+(n1-m1)/2; //printf("%s %s %d %d %d\n",ch[val],pr,m1,n1,val); if(ch[val].compare(0, pr.size(), pr)==0) { cnt++; jiancha_left(val-1,pr); jiancha_right(val+1,pr); break; } else if(pr < ch[val]) n1=val; else m1=val+1; } return cnt; } int main() { int t,m,n; char s[1]; scanf("%d",&t); while(t--) { scanf("%d",&m); for(int i=0;i<m;i++) { cin >> ch[i]; } scanf("%d",&n); for(int i=0;i<n;i++) { cin >> pre[i]; } sort(ch, ch + m); int ans; for(int i=0;i<n;i++) { cnt=0; ans=bbsearch(pre[i],0,m); printf("%d\n",ans); } } }
标签:
原文地址:http://www.cnblogs.com/lonewanderer/p/5697989.html