• 1087: Common Substrings (哈希)


    1087: Common Substrings

    Time Limit:3000/1000 MS (Java/Others)   Memory Limit:163840/131072 KB (Java/Others)
    Total Submissions:857   Accepted:112
    [Submit][Status][Discuss]

    Description

    You are given two long strings A

    and B. They are comprised of lowercase letters. You should compute how many suffixes of A are the prefixes of B

    .

    Input

    In the first line is a number T

    (0<T100

    ) , indicating the cases following.
    In the next T lines each line contains two strings — A

    and B

    .
    ( 0<|A|105,0<|B|105
    )

    Output

    There should be exactly T
    lines.
    Each line contain a number — the answer.

    Sample Input

    1
    abcc ccba

    Sample Output

    2

    HINT

    In the first case, cc and c are two of the suffixes of string A, and they are the prefixes of string B.
    【分析】H[i]-H[L]*xp[L]表示从s[i]开始的长度为L的字符串的哈希值。
     
    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <algorithm>
    #include <cmath>
    #include <string>
    #include <stack>
    #include <queue>
    #include <vector>
    #include <map>
    #define inf 0x3f3f3f3f
    #define met(a,b) memset(a,b,sizeof a)
    #define pb push_back
    using namespace std;
    typedef long long ll;
    const ll N = 1e5+10;
    const int x=123;
    ll H1[N],H2[N],xp[N];
    ll hs1,hs2;
    int ans;
    char stra[N],strb[N];
    int main()
    {
        int T;
        scanf("%d",&T);
        while (T--){
            scanf("%s%s",stra,strb);
            int lena=strlen(stra),lenb=strlen(strb);
            H1[lena]=0,H2[lenb]=0;
            for (int i=lena-1;i>=0;--i)
                H1[i]=H1[i+1]*x+(stra[i]-'a');
            for (int i=lenb-1;i>=0;--i){
                H2[i]=H2[i+1]*x+(strb[i]-'a');
            }
            xp[0]=1;
            ans=0;
            for (int i=1;i<=max(lena,lenb);++i)
                xp[i]=xp[i-1]*x;
            for (int L=1;L<=min(lena,lenb);++L){
                hs2=H2[0]-H2[L]*xp[L];
                hs1=H1[lena-L]-H1[lena]*xp[L];
                if (hs2==hs1)
                    ans++;
            }
            printf("%d
    ",ans);
        }
        return 0;
    }
  • 相关阅读:
    WPF Expander 炫酷自定义Style
    C#8.0 中的 【索引与范围】
    Windows的图形设备接口与Windows绘图
    第一个Windows窗口应用程序
    0-1背包问题的分枝—限界算法
    哈密尔顿回路(旅行售货员问题)的回溯算法
    背包问题的贪心算法
    实现矩阵连乘的动态规划算法
    用分治策略实现棋盘覆盖问题
    sql注入实例分析
  • 原文地址:https://www.cnblogs.com/jianrenfang/p/6549410.html
Copyright © 2020-2023  润新知