HDU 5384 Tire树,我也不知道为什么不会MLE

来源:互联网 发布:免费刷排名软件 编辑:程序博客网 时间:2024/05/01 07:51

题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=5384

题意:
输入n,m
然后又n串字符串A,和m串字符串B
然后输出n行
i th行: 每一个B 在Ai 中出现的次数的和。

开始想:把每一个Ai 拆开 从1-len 分别插入字典树,然后拿m串B去匹配,后来发现无法分别匹配出来的值到底是哪个Ai给的。如果一定要分别出来的话,可能要插入一个A,就扫一遍B,得出值,但肯定会超时。
如果在节点里面插入数组表示第几个A给的V,我又觉得超内存了,真是烦;

如果一个串A 在Tire中,查到了另外一个串B的结尾, 是不是表示B 是 作为A 的一个子串出现的?

正解:把所有的B串都插入到字典树, 只有在每一串的最后一个字母才进行v的相加,然后我们再扫一遍A,每一个A进行拆分查找:即从A[i][0]…A[i][1]…A[i][2]………..A[i][len] 依次匹配字典树。
既可以得出每一个A[i]的匹配值,但是为毛这样不TLE? 这几天多校杭电真的把我搞崩了:
分析一下,n个A ,然后每个n要进行 strlen(stra[i])长度的匹配;我们假设匹配的时间复杂度是O(1), 那么时间复杂度应该是O( n*len)
题目中给的A[i] <1e4 ,n <=1e5
这样来算时间复杂度 应该是1e9 =10E;
还有一种可能就是:因为∑|Ai|≤1e5,而n<=1e5,所以在n最大的情况下,A的平均长度只有1,所以这样子来看就不会TLE。

还有就是,我测试了两个版本。一个是用char存储A串 :

char stra[100005][10010];//string stra[100005];

这样的数组开了 1e9 也是10E,怎么能开的下?居然编译过了,内存也不爆;
当然题目中给出来了∑|Ai|≤1e5,所以我们可以开一个string stra[100005], 然后可以用

findTire(stra[i].c_str()+j);

转换为string,但是这样写在函数中要注意:

__int64 findTire(const char *str){   //只有在这里+写const,才可以用string}


我是真的菜

#include<iostream>#include<stdio.h>#include<string.h>#include<math.h>#include<algorithm>#include<stdlib.h>#include<queue>#include<stack>#include<map>#include<set>#include<vector>const double PI = acos(-1.0);const double e = exp(1.0);template<class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; }template<class T> T lcm(T a, T b) { return a / gcd(a, b) * b; }using namespace std;typedef struct Tire{    int v; //只在终点标记    int next[26];};int ptr=0;Tire word[1000005];/* 虽然知道节省空间,但并不知道为啥 * */void init(int z){    for(int i=0;i<26;i++)        word[z].next[i]=-1,word[z].v=0;  //初始化为-1}void creatTire(char *str,int x){    int len=strlen(str);    int cnt=0;    for(int i=0;i<len;i++){         if(word[cnt].next[str[i]-'a']==-1){             word[cnt].next[str[i]-'a']=++ptr;             init(ptr);   // 相当于初始化新开的节点             cnt=ptr;     // 相当于移位         }         else             cnt=word[cnt].next[str[i]-'a'];        if(i==len-1)            word[cnt].v+=x;    }}__int64 findTire(char *str){    int len=strlen(str);    int cnt=0;    __int64 ans=0;    for(int  i=0;i<len;i++){        int id=str[i]-'a';        if(word[cnt].next[id]==-1){            return ans; // 不存在这个str        }        else            cnt=word[cnt].next[id];        ans+=word[cnt].v;    }    return ans; //查找串是字符串中的前缀}char strb[10010];char stra[100005][10010];int main(){    //freopen("1.txt","r",stain);    int t;    scanf("%d",&t);    int n,m;    while(t--){        init(0);  //  又出现一个特容易忘的init了,要写到t里面去啊       scanf("%d %d",&n,&m);       for(int i=1;i<=n;i++)           scanf("%s",stra[i]);       for(int i=0;i<m;i++){           scanf("%s",strb);           creatTire(strb,1);       }       for(int i=1;i<=n;i++){           int len=strlen(stra[i]);            __int64 cnt=0;           for(int j=0;j<len;j++){               cnt+=findTire(&stra[i][j]);           }           printf("%I64d\n",cnt);       }    }  return 0;}
0 0