【BZOJ 2351】Matrix(Hash)

題目鏈接
二維\(Hash\)類似二維前綴和,每一行看成一個\(h\)進制數,每一個以(1,1)爲左上角的矩陣看成一個由每一行的\(Hash\)值組成的\(l\)進制數。
然後自己推推柿子就行。

#include <cstdio>
#include <cstring>
#include <map>
using namespace std;
#define Open(s) freopen(s".in","r",stdin); freopen(s".out","w",stdout);
#define h 1331
#define l 2333
int n, m, r, c, T;
map <unsigned long long, int> mp;
unsigned long long hs[1010][1010], ph[1010], pl[1010], xs[1010][1010];
char ch;
int main(){
    Open("matrix"); ph[0] = pl[0] = 1;
    scanf("%d%d%d%d", &n, &m, &r, &c);
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= m; ++j){
            ch = getchar();
            while(ch != '0' && ch != '1') ch = getchar();
            hs[i][j] = hs[i][j - 1] * h + ch;
        }
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= m; ++j)
            hs[i][j] += hs[i - 1][j] * l;
    for(int i = 1; i <= m; ++i) ph[i] = ph[i - 1] * h;
    for(int i = 1; i <= n; ++i) pl[i] = pl[i - 1] * l; 
    for(int i = r; i <= n; ++i)
        for(int j = c; j <= m; ++j)
            mp[hs[i][j] - hs[i - r][j] * pl[r] - hs[i][j - c] * ph[c] + hs[i - r][j - c] * pl[r] * ph[c]] = 1;
    scanf("%d", &T);
    while(T--){
        for(int i = 1; i <= r; ++i)
            for(int j = 1; j <= c; ++j)
                xs[i][j] = 0;
        for(int i = 1; i <= r; ++i)
            for(int j = 1; j <= c; ++j){
                ch = getchar();
                while(ch != '0' && ch != '1') ch = getchar();
                xs[i][j] = xs[i][j - 1] * h + ch;
            }
        for(int i = 1; i <= r; ++i)
            for(int j = 1; j <= c; ++j)
                xs[i][j] += xs[i - 1][j] * l;
        printf("%d\n", mp[xs[r][c]]);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章