【codeup墓地】2432: 求最长公共子串(串) (字符串哈希)

原题链接

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

typedef long long int LL;
const int MAX = 10010;
const LL P = 10000019, MOD = 1000000007;

typedef struct Node
{
    string str;//子串
    LL hash_value;///子串哈希值
    int len;//子串长度
}Node;
vector<Node> subS, subT;
string S, T;
Node MAX_LEN = {"", 0, 0};
LL powP[MAX] = {0}, HS[MAX] = {0}, HT[MAX] = {0};

void init(int len)//推算p的指数函数值
{
    powP[0] = 1;
    for(int i=1; i<=len; i++)
    {
        powP[i] = (powP[i-1]*P) % MOD;
    }
}

void calHash(LL H[], string &str)//计算str的从0到i的子串哈希值
{
    H[0] = str[0];
    for(int i=1; i<(int)str.size(); i++)
    {
        H[i] = (H[i-1]*P + str[i]) % MOD;
    }
}

LL calSingleSubHash(LL H[], int i, int j)//推算i到j子串的哈希值
{
    if(!i) return H[j];
    return ((H[j] - H[i-1]*powP[j-i+1]) % MOD + MOD) % MOD;
}

void calSubHash(LL H[], string &str, vector<Node> &subStr)//计算str的每个子串的哈希值
{
    for(int i=0; i<(int)str.size(); i++)
    {
        for(int j=i; j<(int)str.size(); j++)
        {
            LL temp_hash_value = calSingleSubHash(H, i, j);
            Node temp_node = {str.substr(i, j), temp_hash_value, j-i+1};
            subStr.push_back(temp_node);
        }
    }
}

int main()
{
    cin>>S>>T;
    init(max(S.size(), T.size()));
    calHash(HS, S);
    calHash(HT, T);
    calSubHash(HS, S, subS);
    calSubHash(HT, T, subT);
    for(int i=0; i<(int)subS.size(); i++)//根据哈希值判断字符串是否相等
    {
        for(int j=0; j<(int)subT.size(); j++)
        {
            if(subS[i].hash_value == subT[j].hash_value && subS[i].len > MAX_LEN.len)//找到最长子串
            {
                MAX_LEN.hash_value = subS[i].hash_value;
                MAX_LEN.len = subS[i].len;
                MAX_LEN.str = subS[i].str;
            }
        }
    }
    cout<<MAX_LEN.str;
    return 0;
}

你可能感兴趣的:(机试训练)