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 <bits/stdc++.h>
#define ll long long
#define debug if (0)

const ll MOD = 1e9 + 7;

ll fast_pow(ll a, int p) {
  if (p == 0)
    return 1;
  if (p % 2 == 0) {
    ll tmp = fast_pow(a, p / 2);
    return tmp * tmp % MOD;
  }
  return fast_pow(a, p - 1) * a % MOD;
}

ll inv(ll x) { return fast_pow(x, MOD - 2); }

const int MAX_N = 3000;
int n, k;

bool visited[MAX_N + 3][MAX_N + 3];
std::vector<int> nf[MAX_N + 3];

int main() {
  std::ios_base::sync_with_stdio(0);
  std::cin.tie(NULL);
  srand(123534);

  std::cin >> n >> k;

  ll res = 0;
  ll A, B, C;

  std::vector<std::vector<int>> P;
  std::vector<int> p(n + 1, 0);
  for (int i = 1; i <= k; i++) {
    for (int j = 1; j <= n; j++) {
      std::cin >> p[j];
      if (j != p[j])
        nf[j].push_back(i - 1);
    }
    P.push_back(p);
  }

  std::queue<std::pair<int, int>> q;
  int visited_cnt = 0;

  auto check = [&](int &x, int &y, std::vector<int> &p) {
    if (!visited[p[x]][p[y]]) {
      visited_cnt++;
      visited[p[x]][p[y]] = true;
      A++;
      if (p[x] > p[y])
        B++;
      q.push({p[x], p[y]});
    }
  };

  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      if (visited_cnt == n * (n - 1))
        goto end_bfs;

      if (i == j || visited[i][j])
        continue;

      q.push({i, j});
      A = 1;
      if (i > j)
        B = 1;
      else
        B = 0;
      visited[i][j] = true;
      visited_cnt++;

      while (!q.empty()) {
        if (visited_cnt == n * (n - 1))
          goto end_while;

        auto [x, y] = q.front();
        q.pop();

        if (nf[x].size() + nf[y].size() >= k) {
          // all
          for (auto &p : P)
            check(x, y, p);
        } else {
          // not all
          for (auto &i : nf[x]) {
            check(x, y, P[i]);
          }
          for (auto &i : nf[y]) {
            check(x, y, P[i]);
          }
        }
      }

    end_while:

      C = A - B;
      res = (res + (C * B % MOD * inv(A) % MOD)) % MOD;
    }
  }

end_bfs:

  // for (int i = 1; i <= n; i++) {
  //   for (int j = 1; j <= n; j++) {
  //     if (i == j)
  //       continue;
  //     iid = get_id(i, j);
  //     if (find_father(iid) == iid) {
  //       A = size[iid];
  //       B = bad[iid];
  //       C = A - B;
  //       res = (res + (C * B % MOD * inv(A) % MOD)) % MOD;
  //     }
  //   }
  // }

  std::cout << res << "\n";
}