Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///Finding the number of occurs of a string in another string
- #include<bits/stdc++.h>
- using namespace std;
- #define ll long long int
- vector<string>vs;
- struct NODE
- {
- ll cnt,i;
- bool vis;
- NODE *next[60];
- vector<NODE *> out;
- NODE()
- {
- cnt=0;
- vis=false;
- out.clear();
- for(i=0; i<60; i++)
- next[i]=NULL;
- }
- ~NODE()
- {
- for(i=0; i<60; i++)
- if(next[i])
- delete(next[i]);
- }
- };
- NODE *root,*p;
- void aho_corasick(string s)
- {
- ll i,c;
- p=root;
- for(i=0; i<s.size(); i++)
- {
- c=s[i]-'A'+1;
- while(!p->next[c])
- p=p->next[0];
- p=p->next[c];
- p->cnt++;
- }
- }
- void buildtrie()
- {
- ll i,j,c;
- NODE *u,*w,*v;
- root=new NODE;
- queue< NODE* > q;
- ///usual trie part
- for(i=0; i<vs.size(); i++)
- {
- p=root;
- for(j=0; j<vs[i].size(); j++)
- {
- c=vs[i][j]-'A'+1;
- if(!p->next[c])
- p->next[c]=new NODE;
- p=p->next[c];
- }
- }
- /// Pushing the nodes adjacent to root into queue
- for(i=0; i<60; i++)
- {
- if(root->next[i])
- {
- q.push(root->next[i]);
- root->next[i]->next[0]=root; /// ->next[0] = back Pointer
- }
- else
- root->next[i]=root;
- }
- ///Building Aho-Corasick tree
- while(!q.empty())
- {
- u=q.front(); /// parent node
- q.pop();
- for(i=1; i<60; i++)
- {
- if(u->next[i])
- {
- v=u->next[i]; /// child node
- w=u->next[0]; /// back pointer of parent node
- while(!w->next[i]) /// Until the char(i+'a'-1) child is found
- w=w->next[0]; /// go up and up to back pointer.
- w=w->next[i];
- v->next[0]=w; /// back pointer of v will be found child above.
- w->out.push_back(v); /// out will be used in dfs step.
- ///here w is the new found match node.
- q.push(v);
- }
- }
- }
- }
- ll dfs(NODE *p) /// DFS for counting.
- {
- ll i;
- if(p->vis)
- return p->cnt;
- for(i = 0; i < p->out.size(); i++)
- p->cnt += dfs(p->out[i]);
- p->vis = true;
- return p->cnt;
- }
- int main()
- {
- ll T,t,n,i,j,c;
- string s1,s2;
- scanf("%lld",&T);
- for (t = 1; t <= T; t++)
- {
- scanf("%lld",&n);
- cin>>s1;
- vs.clear();
- for(i=0; i<n; i++)
- {
- cin>>s2;
- vs.push_back(s2);
- }
- buildtrie();
- aho_corasick(s1);
- printf("Case %d:\n",t);
- for(i=0; i<n; i++)
- {
- p=root;
- for(j=0; j<vs[i].size(); j++)
- {
- c=vs[i][j]-'A'+1;
- p=p->next[c];
- }
- printf("%lld\n", dfs(p));
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement