【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;
}
posted @ 2019-07-22 10:11  Qihoo360  阅读(157)  评论(0编辑  收藏  举报
You're powerful!