【BZOJ 1590】 Secret Message

【题目链接】

             https://www.lydsy.com/JudgeOnline/problem.php?id=1590

【算法】

           字典树

【代码】

           

#include<bits/stdc++.h>
using namespace std;
#define MAXL 500010

int i,j,n,m,len;
int s[MAXL];

struct info
{
        int child[2];
        int cnt,sum;        
};

class Trie
{
        private :
             int tot;
             info a[MAXL];            
        public :
                inline void insert(int len,int *s)
                {
                        int i,x = 0;
                        for (i = 1; i <= len; i++)
                        {
                                a[x].sum++;
                                if (!a[x].child[s[i]]) a[x].child[s[i]] = ++tot;
                                x = a[x].child[s[i]];
                        }    
                        a[x].cnt++;
                }        
                inline int query(int len,int *s)
                {
                        int i,ret = 0,x = 0;
                        for (i = 1; i <= len; i++)
                        {
                                if (a[x].child[s[i]]) x = a[x].child[s[i]];
                                else return ret;
                                ret += a[x].cnt;
                        }
                        ret += a[x].sum;
                        return ret;
                }
} T;

int main() 
{
        
        scanf("%d%d",&n,&m);
        for (i = 1; i <= n; i++)
        {
                scanf("%d",&len);
                for (j = 1; j <= len; j++) scanf("%d",&s[j]);
                T.insert(len,s);        
        }
        for (i = 1; i <= m; i++)
        {
                scanf("%d",&len);
                for (j = 1; j <= len; j++) scanf("%d",&s[j]);
                printf("%d\n",T.query(len,s));
        }
        
        return 0;
    
}

猜你喜欢

转载自www.cnblogs.com/evenbao/p/9256962.html