链接:https://www.nowcoder.com/acm/contest/2/A
来源:牛客网
题目描述
给出一个n * m的矩阵。让你从中发现一个最大的正方形。使得这样子的正方形在矩阵中出现了至少两次。输出最大正方形的边长。
输入描述:
第一行两个整数n, m代表矩阵的长和宽; 接下来n行,每行m个字符(小写字母),表示矩阵;
输出描述:
输出一个整数表示满足条件的最大正方形的边长。
示例1
输入
复制
5 10 ljkfghdfas isdfjksiye pgljkijlgp eyisdafdsi lnpglkfkjl
输出
复制
3
备注:
对于30%的数据,n,m≤100; 对于100%的数据,n,m≤500;
解题思路:首先想到的二分正方形长度,然后我们对矩阵进行二维哈希一下,这样对于每个子矩阵我们都有对应的一个哈希值,这样我们二分的条件就找该哈希值有没有出现两次即可,出现的次数我们用map来记录一下。
不会哈希的戳这里:哈希算法详解
AC代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<string>
#include<math.h>
#include<cstdlib>
#include<stdlib.h>
#include<queue>
#include<map>
#include<set>
#include<stack>
#define bug printf("*********\n");
#define mem0(a) memset(a, 0, sizeof(a));
#define mem1(a) memset(a, -1, sizeof(a));
#define finf(a, n) fill(a, a+n, INF);
#define in1(a) scanf("%d" ,&a);
#define in2(a, b) scanf("%d%d", &a, &b);
#define in3(a, b, c) scanf("%d%d%d", &a, &b, &c);
#define out1(a) printf("%d\n", a);
#define out2(a, b) printf("%d %d\n", a, b);
#define pb(G, b) G.push_back(b);
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
typedef pair<LL, pair<int, LL> > LLppar;
typedef pair<int, int> par;
typedef pair<LL, int> LLpar;
const LL mod = 2147493647;
const LL INF = 1e9+7;
const uLL base1 = 131;
const uLL base2 = 233;
const int MAXN = 300010;
const int MAXM = 300010;
const double pi = acos(-1);
int n, m;
char mp[510][510];
uLL has[510][510];
uLL p1[510], p2[510];
map<uLL, int> mmp;
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()
{
has[0][0] = 0;
has[0][1] = 0;
has[1][0] = 0;
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= m; j ++) {
has[i][j] = has[i][j-1]*base1 + mp[i][j] - 'a';
}
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j ++) {
has[i][j] = has[i-1][j]*base2 + has[i][j];
}
}
}
bool check(int x)
{
mmp.clear();
for(int i = x; i <= n; i ++) {
for(int j = x; j <= m; j ++) {
uLL k = has[i][j] - has[i-x][j]*p2[x] - has[i][j-x]*p1[x] + has[i-x][j-x]*p1[x]*p2[x];
mmp[k] ++;
if(mmp[k] >= 2) return true;
}
}
return false;
}
int main() {
init();
while(~scanf("%d%d", &n, &m)) {
for(int i = 1; i <= n; i ++) {
scanf("%s", mp[i]+1);
}
Hash();
int l = 0, r = 600, ans = 0;
while(l <= r) {
int mid = (l+r)/2;
if(check(mid)) {
l = mid+1;
ans = mid;
}else {
r = mid-1;
}
}
printf("%d\n", ans);
}
return 0;
}