Advertisement
Riz1Ahmed

Trie Algorithm (LOJ 1224 - DNA Prefix)

Nov 3rd, 2018
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* ******Trie ALGO Problem (LOJ 1224)*******
  2. Given N string (Contain only 'A', 'C', 'G', 'T').
  3. Find a Substring which is Maximum len*t.
  4.     (Here len=Substring size, t=Occurrence time).
  5. °°°°°°°°°°°Input°°°°°°°°°°°
  6. 1 4
  7. ACGT ACGTGCGT ACCGTGC ACGCCGT
  8. °°°°°°°°°Output°°°°°°°°°°°
  9. Case 1: 9
  10. */
  11. #include <bits/stdc++.h>
  12. using namespace std;
  13. int ans;
  14. struct trie{
  15.     trie *eg[5]; int c=0;
  16.     trie(){eg[1]=eg[2]=eg[3]=eg[4]=NULL;}
  17. };
  18. int max(int a,int b){return a>b?a:b;};
  19. int idx(char c){
  20.     if (c=='A') return 1; if (c=='C') return 2;
  21.     if (c=='G') return 3; if (c=='T') return 4;
  22. }
  23. void insert(char s[],trie *r){
  24.     trie *t=r; int l=strlen(s);
  25.     for (int i=0; i<l; i++){
  26.         int x=idx(s[i]);
  27.         if (!t->eg[x]) t->eg[x]=new trie();
  28.         t=t->eg[x], t->c++;
  29.     }
  30. }
  31. void dfs(int p,trie *r){
  32.     ans=max(ans,p*r->c);
  33.     for (int i=1; i<5; i++)
  34.         if (r->eg[i]) dfs(p+1, r->eg[i]);
  35. }
  36. void clean(trie *t){
  37.     for (int i=1; i<5; i++)
  38.         if (t->eg[i]) clean(t->eg[i]);
  39.     free(t);
  40. }
  41. int main(){
  42.     int t,cs=1,n;
  43.     char s[60];
  44.     scanf("%d",&t);
  45.     while (t--){
  46.         trie *r=new trie();
  47.         scanf("%d",&n);
  48.         while (n--) scanf("%s",s), insert(s,r);
  49.         ans=0, dfs(0,r);
  50.         printf("Case %d: %d\n",cs++,ans);
  51.         clean(r);
  52.     } return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement