ybtoj·子正方形【Hash】

子正方形

Description–

高效进阶「字符串算法」第2章 Hash 和 Hash 表课堂过关 例题5


代码–

#include <iostream>
#include <cstdio>
#define ull long long

using namespace std;

int n, ans, a[55][55], b[55][55];
ull t1[55], t2[55], h1[55][55], h2[55][55];

bool xyn(int x, int y, int xr, int yr, int ll) //求这两个矩阵的哈希值
{
	ull aa, bb;
	aa = h1[x][y] - h1[x - ll][y] * t2[ll] - h1[x][y - ll] * t1[ll] + h1[x - ll][y - ll] * t1[ll] * t2[ll];
	bb = h2[xr][yr] - h2[xr - ll][yr] * t2[ll] - h2[xr][yr - ll] * t1[ll] + h2[xr - ll][yr - ll] * t1[ll] * t2[ll];
	return aa == bb;
}

void hll(int x, int y, int xr, int yr) //二分
{
	int l = 0, r = min(min(x, y), min(xr, yr));
	while (l <= r)
	{
		int mid = (l + r + 1) >> 1;
		if (xyn(x, y, xr, yr, mid))
		  l = mid + 1, ans = max(ans, mid);
		else r = mid - 1;
	}
}

int main()
{
	scanf("%d", &n);
	for (int i = 1; i <= n; ++i)
	  for (int j = 1; j <= n; ++j)
	    scanf("%d", &a[i][j]);
	for (int i = 1; i <= n; ++i)
	  for (int j = 1; j <= n; ++j)
	    scanf("%d", &b[i][j]);
	t1[0] = t2[0] = 1;
	for (int i = 1; i <= n; ++i)
	  t1[i] = t1[i - 1] * 131, t2[i] = t2[i - 1] * 61;
	for (int i = 1; i <= n; ++i)
	  for (int j = 1; j <= n; ++j)
	  {
	  	  h1[i][j] = h1[i][j - 1] * 131 + a[i][j];
	  	  h2[i][j] = h2[i][j - 1] * 131 + b[i][j];
	  }
	for (int i = 1; i <= n; ++i)
	  for (int j = 1; j <= n; ++j)
	  {
	  	  h1[i][j] += h1[i - 1][j] * 61;
	  	  h2[i][j] += h2[i - 1][j] * 61;
	  }
	for (int i = 1; i <= n; ++i)
	  for (int j = 1; j <= n; ++j)
	    for (int k = 1; k <= n; ++k)
	      for (int l = 1; l <= n; ++l)
	         if (a[i][j] == b[k][l])
			   hll(i, j, k, l);
	printf("%d", ans);
	
	return 0;
}
上一篇:centos下安装与配置Apache方法


下一篇:flink实战-模拟简易双11实时统计大屏