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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#include <bits/stdc++.h>
using std::cin, std::cout, std::vector;

// Max number of inverse computations:
// n^2 / num_precomputed_inverse + num_precomputed_inverse
// Minimized for n. Maximum n is 3000.
constexpr unsigned num_precomputed_inverse = 3000;

// Stop after this many iterations with no progress.
// False positive probability each time <= 2^-stop_after_iterations.
constexpr unsigned stop_after_iterations = 30;

const std::array<uint32_t, 8> SECRET_KEY = {
    0xe437b3b4,0x995b1423,0x59bfa3dd,0xfab1afc3,0x3c8cdc0,0x98f7554,0x6f77d815,0x921d2ac7,
};

// ===

void init_io() {
  cin.tie(nullptr);
  std::ios::sync_with_stdio(false);
}

namespace chacha_private {
  inline std::uint32_t rotate_left(const std::uint32_t x, int bits) {
    return (x << bits) | (x >> (32 - bits));
  }

  inline void quarter_round(std::uint32_t &a, std::uint32_t &b, std::uint32_t &c, std::uint32_t &d) {
    a += b;
    d ^= a;
    d = rotate_left(d, 16);
    c += d;
    b ^= c;
    b = rotate_left(b, 12);
    a += b;
    d ^= a;
    d = rotate_left(d, 8);
    c += d;
    b ^= c;
    b = rotate_left(b, 7);
  }
}

template<int rounds>
std::array<std::uint32_t, 16> chacha(const std::array<std::uint32_t, 8> &key,
            const std::uint64_t nonce,
            const std::uint64_t counter)
{
  static_assert(rounds == 8 || rounds == 12 || rounds == 20);

  using namespace chacha_private;

  std::array<std::uint32_t, 16> input;
  std::memcpy(input.data() + 0, "expand 32-byte k", 4 * sizeof(std::uint32_t));
  std::memcpy(input.data() + 4, key.data(), 8 * sizeof(std::uint32_t));
  std::memcpy(input.data() + 12, &counter, 2 * sizeof(std::uint32_t));
  std::memcpy(input.data() + 14, &nonce, 2 * sizeof(std::uint32_t));

  std::array<std::uint32_t, 16> x = input;

  for (int double_round = 0; double_round < rounds / 2; ++double_round) {
    quarter_round(x[0], x[4], x[8], x[12]);
    quarter_round(x[1], x[5], x[9], x[13]);
    quarter_round(x[2], x[6], x[10], x[14]);
    quarter_round(x[3], x[7], x[11], x[15]);

    quarter_round(x[0], x[5], x[10], x[15]);
    quarter_round(x[1], x[6], x[11], x[12]);
    quarter_round(x[2], x[7], x[8], x[13]);
    quarter_round(x[3], x[4], x[9], x[14]);
  }

  for (int i = 0; i < 16; ++i) {
    x[i] += input[i];
  }

  return x;
}

class RandomGenerator {
public:
  RandomGenerator(const std::array<uint32_t, 8> &key,
                  const std::uint64_t nonce) :
    m_chacha_key(key),
    m_chacha_nonce(nonce)
  {}

  RandomGenerator(const RandomGenerator &) = delete;
  void operator=(const RandomGenerator &) = delete;

  uint64_t random_bits(int n);

private:
  void refill_number_buffer();
  void refill_bits_buffer();
  void refill_word_buffer();

  std::array<uint32_t, 8> m_chacha_key;
  uint64_t m_chacha_nonce;
  uint64_t m_chacha_counter = 0;

  std::array<uint32_t, 16> m_word_buffer;
  int m_word_buffer_next = 16;

  uint32_t m_bits_buffer = 0;
  int m_bits_left = 0;
};

inline uint64_t RandomGenerator::random_bits(int n) {
  std::uint64_t result = 0;
  while (n > 0) {
    if (n < m_bits_left) {
      result <<= n;
      result |= m_bits_buffer & ((1u << n) - 1u);
      m_bits_buffer >>= n;
      m_bits_left -= n;
      break;
    } else {
      result <<= m_bits_left;
      result |= m_bits_buffer;
      n -= m_bits_left;
      m_bits_buffer = 0;
      m_bits_left = 0;
      refill_bits_buffer();
    }
  }
  return result;
}

inline void RandomGenerator::refill_bits_buffer() {
  if (m_word_buffer_next == 16) {
    refill_word_buffer();
  }
  m_bits_buffer = m_word_buffer[m_word_buffer_next++];
  m_bits_left = 32;
}

inline void RandomGenerator::refill_word_buffer() {
  m_word_buffer = chacha<8>(m_chacha_key, m_chacha_nonce, m_chacha_counter++);
  m_word_buffer_next = 0;
}

template<class T>
T power(T a, unsigned b) {
  T res = T(1);
  while(b) {
    if(b&1u) res *= a;
    b >>= 1;
    a = a*a;
  }
  return res;
}

template<unsigned MOD>
class Modulo {
public:
  Modulo(unsigned x=0):v(x) {}
  unsigned get() const { return v; }
  Modulo operator+(Modulo b) const {
    unsigned res = v+b.v;
    if (res >= MOD) res -= MOD;
    return res;
  }
  void operator+=(Modulo b) { *this = *this + b; }
  Modulo operator-(Modulo b) const { return *this + Modulo(MOD-b.v); }
  void operator-=(Modulo b) { *this = *this - b; }
  Modulo operator*(Modulo b) const { return Modulo(std::uint64_t(v) * b.v % MOD); }
  void operator*=(Modulo b) { *this = *this * b; }
  Modulo inverse() const { return power(*this, MOD-2); }
private:
  unsigned v;
};

// ===

using Mod = Modulo<1'000'000'007>;

vector<Mod> precomputed_inverse;

void precompute_inverses() {
  precomputed_inverse.resize(num_precomputed_inverse);
  for(unsigned x=1; x<num_precomputed_inverse; ++x) {
    precomputed_inverse[x] = Mod(x).inverse();
  }
}

Mod fast_inverse(const Mod x) {
  if (x.get() < num_precomputed_inverse) {
    return precomputed_inverse[x.get()];
  } else {
    return x.inverse();
  }
}

struct PermutationGroup {
  unsigned n;
  vector<vector<unsigned>> generators;

  vector<unsigned> sample(RandomGenerator &rng) const {
    const unsigned n = this->n;
    vector<unsigned> perm(n);
    for (unsigned i=0; i<n; ++i) perm[i] = i;
    vector<unsigned> next = perm;

    for (const vector<unsigned> &g : generators) {
      if (rng.random_bits(1)) {
        for (unsigned i = 0; i<n; ++i) next[i] = perm[g[i]];
      }
      perm.swap(next);
    }
    return perm;
  }
};

PermutationGroup read_permutation_group() {
  PermutationGroup permutation_group;
  unsigned num_generators;
  cin >> permutation_group.n >> num_generators;
  permutation_group.generators.reserve(num_generators);
  for (unsigned gi = 0; gi < num_generators; ++gi) {
    vector<unsigned> perm;
    perm.reserve(permutation_group.n);
    for (unsigned i=0; i<permutation_group.n; ++i) {
      unsigned x;
      cin >> x;
      --x;
      perm.push_back(x);
    }
    permutation_group.generators.push_back(std::move(perm));
  }
  return permutation_group;
}

PermutationGroup read_permutation_group_speedtest() {
  PermutationGroup permutation_group;
  permutation_group.n = 3000;
  unsigned num_generators = 3000;
  std::mt19937 rng(1234);
  permutation_group.generators.reserve(num_generators);
  for (unsigned gi = 0; gi < num_generators; ++gi) {
    vector<unsigned> perm(permutation_group.n);
    for (unsigned i = 0; i<permutation_group.n; ++i) {
      perm[i] = i;
    }
    std::shuffle(perm.begin(), perm.end(), rng);
    permutation_group.generators.push_back(std::move(perm));
  }
  return permutation_group;
}

class AverageInversionsCalculator {
public:
  explicit AverageInversionsCalculator(const unsigned n1) {
    n = n1;
    group_index.resize(n);
    groups.reserve(n * n);
    for (unsigned a = 0; a < n; ++a) {
      vector<unsigned> &row = group_index[a];
      row.reserve(n);
      for (unsigned b = 0; b < n; ++b) {
        row.push_back(groups.size());
        vector<std::pair<std::uint16_t, std::uint16_t>> g = {{a, b}};
        groups.push_back(std::move(g));
      }
    }
  }

  bool process_permutation(const vector<unsigned> &perm) {
    vector<std::uint8_t> done_row(n, 0);
    bool progress = false;
    for (unsigned i = 0; i < n; ++i) {
      unsigned a = i;
      while (!done_row[a]) {
        if (process_row(a, perm)) {
          progress = true;
        }
        done_row[a] = 1;
        a = perm[a];
      }
    }
    return progress;
  }

  Mod average_inversions() const {
    Mod res(0);
    for (const auto &group : groups) {
      unsigned count_noninverted = 0;
      unsigned count_inverted = 0;
      unsigned count_equal = 0;
      for (const auto &p : group) {
        if (p.first < p.second) {
          ++count_noninverted;
        } else if (p.first > p.second) {
          ++count_inverted;
        } else {
          ++count_equal;
        }
      }
      const unsigned total = count_inverted + count_noninverted;
      if (count_equal == 0 && total != 0) {
        // Each non-inverted has probability count_inverted / total of getting inverted.
        res += Mod(count_noninverted) * Mod(count_inverted) * fast_inverse(Mod(total));
      }
    }
    return res;
  }

private:
  bool process_row(const unsigned y, const vector<unsigned> &perm) {
    const vector<unsigned> &row = group_index[y];
    const vector<unsigned> &row2 = group_index[perm[y]];
    const unsigned n = this->n;
    bool progress = false;
    for (unsigned i = 0; i < n; ++i) {
      const unsigned group1 = row[i];
      const unsigned group2 = row2[perm[i]];
      if (group1 != group2) {
        merge_groups(group1, group2);
        progress = true;
      }
    }
    return progress;
  }

  void merge_groups(unsigned ga, unsigned gb) {
    if (groups[ga].size() < groups[gb].size()) {
      std::swap(ga, gb);
    }
    // gb becomes ga
    for (const auto &p : groups[gb]) {
      group_index[p.first][p.second] = ga;
    }
    groups[ga].insert(groups[ga].end(), groups[gb].begin(), groups[gb].end());
    groups[gb].clear();
    groups[gb].shrink_to_fit();
  }

  unsigned n;
  vector<vector<unsigned>> group_index;
  vector<vector<std::pair<std::uint16_t, std::uint16_t>>> groups;
};

Mod average_inversions(const PermutationGroup &permutation_group) {
  unsigned n = permutation_group.n;
  AverageInversionsCalculator calculator(n);
  unsigned iterations = 0;
  unsigned last_progress = 0;
  RandomGenerator rng(SECRET_KEY, 0);
  while (iterations < last_progress + stop_after_iterations) {
    const vector<unsigned> perm = permutation_group.sample(rng);
    ++iterations;
    if (calculator.process_permutation(perm)) {
      last_progress = iterations;
    }
  }
  std::cerr << "iters: " << last_progress << "+" << (iterations - last_progress) << "\n";
  return calculator.average_inversions();
}

int main() {
  init_io();
  precompute_inverses();

  const PermutationGroup permutation_group = read_permutation_group();
  const Mod result = average_inversions(permutation_group);
  cout << result.get() << "\n";
}