#pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; #include using namespace atcoder; using mint = modint998244353; #define rep(i, n) for (ll i = 0; i < n; i++) #define ALL(a) (a).begin(), (a).end() void chmin(ll &a, ll b) { if (a > b) a = b; } void chmax(ll &a, ll b) { if (a < b) a = b; } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int h, w; cin >> h >> w; vector ss(h); for (int i = 0; i < h; i++) { cin >> ss[i]; } vector> s(h, vector(w)); for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) s[i][j] = ss[i][j] - 'a'; vector> yu(h, vector(w)), ha(h, vector(w)); const int inf = 5e7; vector size(h + w - 1); for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) size[i + j]++; for (int i, j, ij = h + w - 3; ij >= 0; ij--) { int ii = 0, jj = ij; if (jj >= w) { int sa = jj - w + 1; ii += sa; jj -= sa; } i = ii; j = jj; vector hash(size[ij]); int count = 0; while (i < h && j >= 0) { hash[count++] = ha[i][j] = s[i][j] * inf + min(i == h - 1 ? inf : yu[i + 1][j], j == w - 1 ? inf : yu[i][j + 1]); i++; j--; } i = ii; j = jj; sort(ALL(hash)); while (i < h && j >= 0) { int ok = 0, ng = size[ij]; while (ng - ok != 1) { int vs = (ok + ng) >> 1; if (hash[vs] <= ha[i][j]) ok = vs; else ng = vs; } yu[i][j] = ok; i++; j--; } } int i = 0, j = 0; while (j != w) { cout << ss[i][j]; if (i == h - 1) j++; else if (j == w - 1) i++; else { int hi = yu[i + 1][j], hj = yu[i][j + 1]; if (hi < hj) i++; else j++; } } return 0; }