1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <ranges>
#include <set>
#include <string>
#include <vector>

using namespace std;

typedef pair<int, int> PII;

int n = 2, m;
int nm;

vector<vector<int>> a;
vector<PII> rev_a;

int cc;
vector<int> p, rnk;

void init(int x) {
    p[x] = x;
    rnk[x] = 1;
    cc++;
}

int find(int x) {
    if (p[x] == x) return x;
    int res = find(p[x]);
    p[x] = res;
    return res;
}

void merge(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y) return;
    cc--;
    if (rnk[x] > rnk[y]) swap(x, y);
    p[x] = y;
    rnk[y] += rnk[x];
}

vector<int> dx = {1, 0, -1, 0};
vector<int> dy = {0, 1, 0, -1};

array<int, 3> adj(int i) {
    auto get = [&](int x, int y) -> PII {
        if (x < 0 || x >= n) return {-1, -1};
        y = (y + m) % m;
        return {x, y};
    };

    auto [x, y] = rev_a[i];
    array<int, 3> res;
    int k = 0;
    for (int j = 0; j < dx.size(); j++) {
        auto [xx, yy] = get(x + dx[j], y + dy[j]);
        if (xx == -1) continue;
        res[k++] = a[xx][yy];
    }
    assert(k == 3);
    return res;
}

vector<int> res;

void g(int l, int r) {
    init(r);
    auto valid = [&](int x) { return l <= x && x <= r; };
    for (auto j : adj(r))
        if (valid(j)) merge(r, j);
    if (cc < res.size()) res[cc]++;
}

void f(int l) {
    cc = 0;
    p.resize(nm + 1);
    rnk.resize(nm + 1);
    for (int r = l; r <= nm; r++) g(l, r);
}

void solve() {
    int k;
    cin >> m >> k;
    nm = n * m;

    a.resize(n);

    for (int i = 0; i < n; i++) {
        a[i].resize(m);
        for (int j = 0; j < m; j++) cin >> a[i][j];
    }

    rev_a.resize(nm + 1);

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            rev_a[a[i][j]] = {i, j};
        }
    }

    res.resize(k + 1);

    for (int l = 1; l <= nm; l++) f(l);
    for (int i = 1; i <= k; i++) cout << res[i] << " ";
    cout << endl;
}

int main() {
    ios::sync_with_stdio(false);
    cin.exceptions(cin.failbit);
    cin.tie(0);
    solve();
}