CodeForces - 958A2(二维hash)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenquanwei_/article/details/79974505

链接:CodeForces - 958A2

题意:给出N*M和M*N的两个矩阵,要求在两个矩阵中找出M*M的相同部分。

题解:二维hash模板

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

const int maxn = 200;
int N, M;
char a[maxn][maxn], b[maxn][maxn];
unsigned long long ha[maxn][maxn], hb[maxn][maxn], tmp[maxn][maxn];

void CalcHash(unsigned long long h[][maxn], char a[][maxn], int n, int m)
{
    const unsigned long long B1 = 9973;
    const unsigned long long B2 = 1e8 + 7;

    unsigned long long t1 = 1;
    for(int j = 0; j < M; j++) t1 *= B1;

    for(int i = 0; i < n; i++){
        unsigned long long e = 0;
        for(int j = 0; j < M; j++) e = e * B1 + a[i][j];

        for(int j = 0; j + M <= m; j++){
            tmp[i][j] = e;
            if(j + M < m) e = e * B1 - t1 * a[i][j] + a[i][j + M];
        }
    }

    unsigned long long t2 = 1;
    for(int i = 0; i < M; i++) t2 *= B2;

    for(int j = 0; j + M <= m; j++){
        unsigned long long e = 0;
        for(int i = 0; i < M; i++) e = e * B2 + tmp[i][j];

        for(int i = 0; i + M <= n; i++){
            h[i][j] = e;
            if(i + M < n) e = e * B2 - t2 * tmp[i][j] + tmp[i + M][j];
        }
    }

}

void Find(int& x, int& y)
{
    for(int i = 0; i + M <= N; i++){
        for(int j = 0; j + M <= N; j++){
            if(ha[i][0] == hb[0][j]){
                x = i + 1;
                y = j + 1;
                return ;
            }
        }
    }
}

int main()
{
    scanf("%d%d", &N, &M);
    for(int i = 0; i < N; i++) scanf("%s", a[i]);
    for(int i = 0; i < M; i++) scanf("%s", b[i]);

    CalcHash(ha, a, N, M);
    CalcHash(hb, b, M, N);

    int x = 0, y = 0;
    Find(x, y);

    printf("%d %d\n", x, y);

    return 0;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页