Riz1Ahmed

Trie Algorithm (LOJ 1224 DNA Prefix)

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