This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define file(name) if (fopen(name".inp", "r")) { freopen(name".inp", "r", stdin); freopen(name".out", "w", stdout); }
#define FOR(i, a, b) for(int i = (a); i <= (b); ++i)
#define REV(i, b, a) for(int i = (b); i >= (a); --i)
#define REP(i, n) for(int i = 0; i < (n); ++i)
#define ll long long
#define fi first
#define se second
#define int long long
using namespace std;
const int N = 1005;
const int MOD = 1e9 + 7;
char s[2 * N][2 * N];
int pwx[2 * N], pwy[2 * N];
int h[2 * N][2 * N];
int n, m;
int basex = 31, basey = 11111;
void init_hash() {
pwx[0] = pwy[0] = 1;
for(int i = 1; i < 2 * N; ++i) {
pwx[i] = pwx[i - 1] * basex % MOD;
}
for(int i = 1; i < 2 * N; ++i) {
pwy[i] = pwy[i - 1] * basey % MOD;
}
FOR(i, 1, 2 * n) {
FOR(j, 1, 2 * m) {
h[i][j] = (h[i][j - 1] * basex % MOD + s[i][j]) % MOD;
}
}
FOR(j, 1, 2 * m) {
FOR(i, 1, 2 * n) {
h[i][j] = (h[i - 1][j] * basey % MOD + h[i][j]) % MOD;
}
}
}
int getHash(int a, int b, int X,int Y){
int x = a + X - 1;
int y = b + Y - 1;
int ans = (h[x][y] - h[x][b - 1] * pwx[y - b + 1] % MOD - h[a - 1][y] * pwy[x - a + 1] % MOD + MOD) % MOD;
ans = (ans + h[a - 1][b - 1]*pwy[x - a + 1] % MOD * pwx[y - b + 1]) % MOD;
return ans;
}
void solve(int tc) {
cin >> n >> m;
FOR(i, 1, n) {
FOR(j, 1, m) {
cin >> s[i][j];
s[i + n][j] = s[i][j + m] = s[i + n][j + m] = s[i][j];
}
}
init_hash();
int a1 = 1, a2 = 1;
FOR(i, 1, n) {
FOR(j, 1, m) {
int l = i - 1, r = i + n - 1, mid, res = 0;
while(l <= r) {
mid = l + r >> 1;
if(getHash(i, j, mid - i + 1, m) == getHash(a1, a2, mid - i + 1, m)) {
res = mid;
l = mid + 1;
} else r = mid - 1;
}
int row = res + 1;
l = j - 1; r = j + m - 1, res = 0;
while(l <= r) {
mid = l + r >> 1;
if(getHash(row, j, 1, mid - j + 1) == getHash(a1 + (row - i), a2, 1, mid - j + 1)) {
res = mid;
l = mid + 1;
} else r = mid - 1;
}
int col = res + 1;
if(row <= i + n - 1 && col <= j + m - 1 && s[row][col] < s[a1 + (row - i)][a2 + (col - j)]) {
a1 = i, a2 = j;
}
}
}
for(int i = a1; i <= a1 + n - 1; ++i) {for(int j = a2; j <= a2 + m - 1; ++j) {
cout << s[i][j];
}cout << '\n';}
return;
}
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int tc = 1;
// cin >> tc;
for(int i = 1; i <= tc; ++i) solve(tc);
return (0);
}
Compilation message (stderr)
Main.cpp: In function 'void solve(long long int)':
Main.cpp:63:25: warning: suggest parentheses around '+' inside '>>' [-Wparentheses]
63 | mid = l + r >> 1;
| ~~^~~
Main.cpp:72:25: warning: suggest parentheses around '+' inside '>>' [-Wparentheses]
72 | mid = l + r >> 1;
| ~~^~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |