二维字符串 hash

矩阵

给定一个M行N列的01矩阵(只包含数字0或1的矩阵),再执行Q次询问,每次询问给出一个A行B列的01矩阵,求该矩阵是否在原矩阵中出现过。

输入格式

第一行四个整数M,N,A,B。

接下来一个M行N列的01矩阵,数字之间没有空格。

接下来一个整数Q。

接下来Q个A行B列的01矩阵,数字之间没有空格。

输出格式

对于每个询问,输出1表示出现过,0表示没有出现过。

数据范围

A≤100,M,N,B≤1000,Q≤1000

输入样例:

3 3 2 2
111
000
111
3
11
00
11
11
00
11

输出样例

1
0
1
#include <iostream>
#include <algorithm>
#include <cstring>
#include <unordered_set>

using namespace std;

typedef unsigned long long ULL;

const int N = 1010, M = N * N, P = 131;

char str[N];
ULL f[N][N], p[M];

int n, m, a, b;

// 求区间 hash 值
ULL get(ULL f[], int l, int r) {
    
    
    return f[r] - f[l - 1] * p[r - l + 1];
}

int main() {
    
    
    cin >> n >> m >> a >> b;
    // 求取 P 进制数组
    p[0] = 1;
    for (int i = 1; i <= m * n; i ++) p[i] = p[i - 1] * P;
    
    for (int i = 1; i <= n; i ++) {
    
    
        scanf("%s", str + 1);
        // 预先将每一行 hash 化
        for (int j = 1; j <= m; j ++) f[i][j] = f[i][j - 1] * P + str[j] - '0';
    }
    
    // 枚举每一个 a * b 的矩阵,将 hash 值填入 set 中
    unordered_set<ULL> hash;
    for (int i = b; i <= m; i ++) {
    
    
        ULL s = 0;
        int l = i - b + 1, r = i;
        for (int j = 1; j <= n; j ++) {
    
    
        	// 获取以当前行的结尾矩阵 hash 值
            s = s * p[b] + get(f[j], l, r);
            // 将当前行的 hash 值 - 第一行的 hash 值
            if (j > a) s -= get(f[j - a], l, r) * p[a * b];
            // 将该矩阵的 hash 值放入 set
            if (j >= a) hash.insert(s);
        }
    }
    
    int k;
    cin >> k;
    while (k --) {
    
    
        ULL s = 0;
        for (int i = 0; i < a; i ++) {
    
    
            scanf("%s", str);
            // 求出当前行的 hash 值
            for (int j = 0; j < b; j ++) s = s * P + str[j] - '0';
        }
        // 判断 set 中是否存在该矩阵
        if (hash.count(s)) puts("1");
        else puts("0");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/LiAiZu/article/details/113095343