NYOJ--5

 原题链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=5

分析:代码比较长,用到了字典树。

Binary String Matching

  1  
  2 #include<cstdio>
  3 #include<cstring>
  4 #include<iostream>
  5 using namespace std;
  6 #define LEN sizeof(struct Trie)
  7 typedef struct Trie
  8 {
  9     struct Trie *next[2];
 10 }Trie;
 11 char B[1005],A[15];
 12 int K,alloc;
 13 Trie Memory[11000];
 14 
 15 Trie * Newnode()
 16 {
 17     int i;
 18     for(i=0;i<2;i++)
 19         Memory[alloc].next[i]=NULL;
 20     return &Memory[alloc++];
 21 }
 22 int BuildTrie(Trie *root)
 23 {
 24     int len,id,id1,id2,i,k,j,ans=0,count;
 25     Trie *p;
 26     len=strlen(B);
 27     for(i=0;i<len-K+1;i++)
 28     {
 29         j=0;count=0;
 30         if(A[0]!=B[i])continue;
 31         p=root;
 32         id=B[i]-'0';
 33         k=i;
 34         if(p->next[id]==NULL)
 35         {
 36              id1=B[k]-'0';
 37              while(p->next[id1]==NULL&&k<len)
 38              {
 39                   p->next[id1]=Newnode();
 40                   p=p->next[id1];
 41                   count++;
 42                   if(B[k]!=A[j++])break;
 43                   else if(count==K)ans++;
 44                   if(count==K)break;
 45                   k++;
 46                   if(B[k]!='\0')
 47                   id1=B[k]-'0';
 48              }
 49         }
 50         else
 51         {
 52             id2=B[k]-'0';
 53             while(p->next[id2]!=NULL&&k<len)
 54             {
 55                 if(B[k]==A[j++])count++;
 56                 if(count==K)ans++;
 57                 if(count==K)break;
 58                 p=p->next[id2];
 59                 k++;
 60                 if(B[k]!='\0')
 61                 id2=B[k]-'0';
 62             }
 63             if(count<K)
 64             while(p->next[id2]==NULL&&k<len)
 65             {
 66                 p->next[id2]=Newnode();
 67                 p=p->next[id2];
 68                 count++;
 69                 if(B[k]!=A[j++])break;
 70                 else if(count==K)ans++;
 71                 if(count==K)break;
 72                 k++;
 73                 if(B[k]!='\0')
 74                 id1=B[k]-'0';
 75              }
 76         }
 77     }
 78 
 79     return ans;
 80 }
 81 
 82 int main()
 83 {
 84     int T,i,res;
 85     scanf("%d",&T);
 86     while(T--)
 87     {
 88         alloc=0;
 89         Trie *Root=Newnode();
 90         memset(A,0,sizeof(A));
 91         memset(B,0,sizeof(B));
 92         scanf("%s",A);
 93         scanf("%s",B);
 94         K=strlen(A);
 95         res=BuildTrie(Root);
 96         printf("%d\n",res);
 97     }
 98     return 0;
 99 }
100 
101         

 

posted @ 2013-05-31 21:40  EtheGreat  阅读(164)  评论(0)    收藏  举报