#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define f first
#define s second
const int N = 2e3 + 7, base1 = 311, base2 = 10007, MOD = 1e9 + 7;
int n, m;
ll pw[N], pw2[N], h[N][N];
char a[N][N];
void prepare() {
pw[0] = pw2[0] = 1;
for (int i = 1; i <= 2 * n; i++) pw[i] = pw[i - 1] * base1 % MOD;
for (int i = 1; i <= 2 * m; i++) pw2[i] = pw2[i - 1] * base2 % MOD;
for (int i = 1; i <= 2 * n; i++){
for (int j = 1; j <= 2 * m; j++) {
h[i][j] = (h[i - 1][j] * base1 % MOD + h[i][j - 1] * base2 % MOD) % MOD;
(h[i][j] -= h[i - 1][j - 1] * base1 * base2 % MOD + a[i][j] - 'a' + 1) %= MOD;
}
}
}
int get(int a, int b, int x, int y) {
ll ret = (h[x][y] - h[a - 1][y] * pw[x - a + 1] % MOD - h[x][b - 1] * pw2[y - b + 1] + 1ll * MOD * MOD) % MOD;
(ret += h[a - 1][b - 1] * pw[x - a + 1] % MOD * pw2[y - b + 1] % MOD + 1ll * MOD * MOD) %= MOD;
return ret;
}
signed main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
a[i][j + m] = a[i][j];
a[i + n][j] = a[i][j];
a[i + n][j + m] = a[i][j];
}
}
prepare();
pair<int, int> pos = {1, 1};
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
int l = 1, r = n, ans = -1, ans1 = -1;
while (l <= r) {
int mid = l + r >> 1;
if (get(i, j, i + mid - 1, j + m - 1) == get(pos.f, pos.s, pos.f + mid - 1, pos.s + m - 1)) l = mid + 1;
else ans = mid, r = mid - 1;
}
if (ans == -1) continue;
l = 1, r = m;
while (l <= r) {
int mid = l + r >> 1;
if (get(i, j, i + ans - 1, j + mid - 1) == get(pos.f, pos.s, pos.f + ans - 1, pos.s + mid - 1)) l = mid + 1;
else ans1 = mid, r = mid - 1;
}
if (ans1 == -1) continue;
if (a[i + ans - 1][j + ans1 - 1] < a[pos.f + ans - 1][pos.s + ans1 - 1]) pos = {i, j};
}
for (int i = pos.f; i < pos.f + n; i++) {
for (int j = pos.s; j < pos.s + m; j++)
cout << a[i][j];
cout << '\n';
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |