链接:https://ac.nowcoder.com/acm/problem/13610
来源:牛客网
矩阵
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld
题目描述
给出一个n * m的矩阵。让你从中发现一个最大的正方形。使得这样子的正方形在矩阵中出现了至少两次。输出最大正方形的边长。
输入描述:
第一行两个整数n, m代表矩阵的长和宽;
接下来n行,每行m个字符(小写字母),表示矩阵;
输出描述:
输出一个整数表示满足条件的最大正方形的边长。
示例1
输入
复制
5 10
ljkfghdfas
isdfjksiye
pgljkijlgp
eyisdafdsi
lnpglkfkjl
输出
复制
3
备注:
对于30%的数据,n,m≤100;
对于100%的数据,n,m≤500;
这题是个狼灭(狠人), 看题解看了半天才看懂别人的思路, (菜是原罪QAQ)
首先建立一个公式,每一个字母都对应一个数值,然后累加求二维前缀和,此时最右下角的值就是整个矩阵所有字母的hash值的和,
每一次查找是否有两个边长为x的正方形相同,只需从[ x ] [ x ]开始枚举每一个边长为x的正方形矩阵,
因为每一次查找都需要枚举,是相当耗时间的,所以用二分来减少查找次数,
#include<bits/stdc++.h>
using namespace std;
using lom = unsigned long long;
const lom base1 = 131, base2 = 233;
const int M = 505;
int n, m;
char a[M][M];
lom _hash[M][M];
lom p1[M], p2[M];
void init()//初始化
{
p1[0] = p2[0] = 1;
for(int i = 1; i <= 505; i++)
{
p1[i] = p1[i-1] * base1;
p2[i] = p2[i-1] * base2;
}
}
void Hash() //建立hash映射
{
_hash[0][0] = _hash[0][1] = _hash[1][0] = 0;
for(int i = 1; i <= n; i++)//前缀和
for(int j = 1; j <= m; j++)
_hash[i][j] = _hash[i][j-1] * base1 + a[i][j] - 'a';
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)//二维前缀和
_hash[i][j] += _hash[i-1][j] * base2;
}
bool check(int x) //是否存在两个边长为x的矩阵 相同
{
map<lom,int> M;
lom k;
for(int i = x; i <= n; i++)
for(int j = x; j <= m; j++)
{
k = _hash[i][j] - _hash[i-x][j] * p2[x] - _hash[i][j-x] * p1[x];
//减去上边的长方形,减去左面的长方形
k += _hash[i-x][j-x] * p1[x] * p2[x];
//加上多减去的左上角的矩阵
M[k]++;
if(M[k] >= 2) return true;
}
return false;
}
int main()
{
init();
cin >> n >> m;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
cin >> a[i][j];
Hash();
int l = 1, r = max(n, m), ans = 0;
while(l <= r)
{
int mid = (l + r) / 2;
if(check(mid))
{
l = mid + 1;
ans = mid;
}
else
r = mid - 1;
}
cout << ans << endl;
return 0;
}
// God bless me