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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// #pragma GCC optimize("O3,unroll-loops")
#include <bits/stdc++.h>
// #include <x86intrin.h>
using namespace std;
#if __cplusplus >= 202002L
using namespace numbers;
#endif

template<class data_t, data_t _mod>
struct modular_fixed_base{
#define IS_INTEGRAL(T) (is_integral_v<T> || is_same_v<T, __int128_t> || is_same_v<T, __uint128_t>)
#define IS_UNSIGNED(T) (is_unsigned_v<T> || is_same_v<T, __uint128_t>)
	static_assert(IS_UNSIGNED(data_t));
	static_assert(_mod >= 1);
	static constexpr bool VARIATE_MOD_FLAG = false;
	static constexpr data_t mod(){
		return _mod;
	}
	template<class T>
	static vector<modular_fixed_base> precalc_power(T base, int SZ){
		vector<modular_fixed_base> res(SZ + 1, 1);
		for(auto i = 1; i <= SZ; ++ i) res[i] = res[i - 1] * base;
		return res;
	}	
	static vector<modular_fixed_base> _INV;
	static void precalc_inverse(int SZ){
		if(_INV.empty()) _INV.assign(2, 1);
		for(auto x = _INV.size(); x <= SZ; ++ x) _INV.push_back(_mod / x * -_INV[_mod % x]);
	}
	// _mod must be a prime
	static modular_fixed_base _primitive_root;
	static modular_fixed_base primitive_root(){
		if(_primitive_root) return _primitive_root;
		if(_mod == 2) return _primitive_root = 1;
		if(_mod == 998244353) return _primitive_root = 3;
		data_t divs[20] = {};
		divs[0] = 2;
		int cnt = 1;
		data_t x = (_mod - 1) / 2;
		while(x % 2 == 0) x /= 2;
		for(auto i = 3; 1LL * i * i <= x; i += 2){
			if(x % i == 0){
				divs[cnt ++] = i;
				while(x % i == 0) x /= i;
			}
		}
		if(x > 1) divs[cnt ++] = x;
		for(auto g = 2; ; ++ g){
			bool ok = true;
			for(auto i = 0; i < cnt; ++ i){
				if((modular_fixed_base(g).power((_mod - 1) / divs[i])) == 1){
					ok = false;
					break;
				}
			}
			if(ok) return _primitive_root = g;
		}
	}
	constexpr modular_fixed_base(){ }
	modular_fixed_base(const double &x){ data = _normalize(llround(x)); }
	modular_fixed_base(const long double &x){ data = _normalize(llround(x)); }
	template<class T, typename enable_if<IS_INTEGRAL(T)>::type* = nullptr> modular_fixed_base(const T &x){ data = _normalize(x); }
	template<class T, typename enable_if<IS_INTEGRAL(T)>::type* = nullptr> static data_t _normalize(const T &x){
		int sign = x >= 0 ? 1 : -1;
		data_t v =  _mod <= sign * x ? sign * x % _mod : sign * x;
		if(sign == -1 && v) v = _mod - v;
		return v;
	}
	template<class T, typename enable_if<IS_INTEGRAL(T)>::type* = nullptr> operator T() const{ return data; }
	modular_fixed_base &operator+=(const modular_fixed_base &otr){ if((data += otr.data) >= _mod) data -= _mod; return *this; }
	modular_fixed_base &operator-=(const modular_fixed_base &otr){ if((data += _mod - otr.data) >= _mod) data -= _mod; return *this; }
	template<class T, typename enable_if<IS_INTEGRAL(T)>::type* = nullptr> modular_fixed_base &operator+=(const T &otr){ return *this += modular_fixed_base(otr); }
	template<class T, typename enable_if<IS_INTEGRAL(T)>::type* = nullptr> modular_fixed_base &operator-=(const T &otr){ return *this -= modular_fixed_base(otr); }
	modular_fixed_base &operator++(){ return *this += 1; }
	modular_fixed_base &operator--(){ return *this += _mod - 1; }
	modular_fixed_base operator++(int){ modular_fixed_base result(*this); *this += 1; return result; }
	modular_fixed_base operator--(int){ modular_fixed_base result(*this); *this += _mod - 1; return result; }
	modular_fixed_base operator-() const{ return modular_fixed_base(_mod - data); }
	modular_fixed_base &operator*=(const modular_fixed_base &rhs){
		if constexpr(is_same_v<data_t, unsigned int>) data = (unsigned long long)data * rhs.data % _mod;
		else if constexpr(is_same_v<data_t, unsigned long long>){
			long long res = data * rhs.data - _mod * (unsigned long long)(1.L / _mod * data * rhs.data);
			data = res + _mod * (res < 0) - _mod * (res >= (long long)_mod);
		}
		else data = _normalize(data * rhs.data);
		return *this;
	}
	template<class T, typename enable_if<IS_INTEGRAL(T)>::type* = nullptr>
	modular_fixed_base &inplace_power(T e){
		if(e == 0) return *this = 1;
		if(data == 0) return *this = {};
		if(data == 1) return *this;
		if(data == mod() - 1) return e % 2 ? *this : *this = -*this;
		if(e < 0) *this = 1 / *this, e = -e;
		modular_fixed_base res = 1;
		for(; e; *this *= *this, e >>= 1) if(e & 1) res *= *this;
		return *this = res;
	}
	template<class T, typename enable_if<IS_INTEGRAL(T)>::type* = nullptr>
	modular_fixed_base power(T e) const{
		return modular_fixed_base(*this).inplace_power(e);
	}
	modular_fixed_base &operator/=(const modular_fixed_base &otr){
		make_signed_t<data_t> a = otr.data, m = _mod, u = 0, v = 1;
		if(a < _INV.size()) return *this *= _INV[a];
		while(a){
			make_signed_t<data_t> t = m / a;
			m -= t * a; swap(a, m);
			u -= t * v; swap(u, v);
		}
		assert(m == 1);
		return *this *= u;
	}
#define ARITHMETIC_OP(op, apply_op)\
modular_fixed_base operator op(const modular_fixed_base &x) const{ return modular_fixed_base(*this) apply_op x; }\
template<class T, typename enable_if<IS_INTEGRAL(T)>::type* = nullptr>\
modular_fixed_base operator op(const T &x) const{ return modular_fixed_base(*this) apply_op modular_fixed_base(x); }\
template<class T, typename enable_if<IS_INTEGRAL(T)>::type* = nullptr>\
friend modular_fixed_base operator op(const T &x, const modular_fixed_base &y){ return modular_fixed_base(x) apply_op y; }
	ARITHMETIC_OP(+, +=) ARITHMETIC_OP(-, -=) ARITHMETIC_OP(*, *=) ARITHMETIC_OP(/, /=)
#undef ARITHMETIC_OP
#define COMPARE_OP(op)\
bool operator op(const modular_fixed_base &x) const{ return data op x.data; }\
template<class T, typename enable_if<IS_INTEGRAL(T)>::type* = nullptr>\
bool operator op(const T &x) const{ return data op modular_fixed_base(x).data; }\
template<class T, typename enable_if<IS_INTEGRAL(T)>::type* = nullptr>\
friend bool operator op(const T &x, const modular_fixed_base &y){ return modular_fixed_base(x).data op y.data; }
	COMPARE_OP(==) COMPARE_OP(!=) COMPARE_OP(<) COMPARE_OP(<=) COMPARE_OP(>) COMPARE_OP(>=)
#undef COMPARE_OP
	friend istream &operator>>(istream &in, modular_fixed_base &number){
		long long x;
		in >> x;
		number.data = modular_fixed_base::_normalize(x);
		return in;
	}
#define _SHOW_FRACTION
	friend ostream &operator<<(ostream &out, const modular_fixed_base &number){
		out << number.data;
	#if defined(LOCAL) && defined(_SHOW_FRACTION)
		cerr << "(";
		for(auto d = 1; ; ++ d){
			if((number * d).data <= 1000000){
				cerr << (number * d).data;
				if(d != 1) cerr << "/" << d;
				break;
			}
			else if((-number * d).data <= 1000000){
				cerr << "-" << (-number * d).data;
				if(d != 1) cerr << "/" << d;
				break;
			}
		}
		cerr << ")";
	#endif
		return out;
	}
	data_t data = 0;
#undef _SHOW_FRACTION
#undef IS_INTEGRAL
#undef IS_SIGNED
};
template<class data_t, data_t _mod> vector<modular_fixed_base<data_t, _mod>> modular_fixed_base<data_t, _mod>::_INV;
template<class data_t, data_t _mod> modular_fixed_base<data_t, _mod> modular_fixed_base<data_t, _mod>::_primitive_root;

// const unsigned int mod = (119 << 23) + 1; // 998244353
const unsigned int mod = 1e9 + 7; // 1000000007
// const unsigned int mod = 1e9 + 9; // 1000000009
// const unsigned long long mod = (unsigned long long)1e18 + 9;
using modular = modular_fixed_base<decay_t<decltype(mod)>, mod>;

// O(n * log(n))
template<class T, class Compare = less<>>
long long count_inversions(const vector<T> &a, bool count_equal = false, Compare cmp = less<>()){
	int n = (int)a.size();
	vector<T> cmpr = a;
	sort(cmpr.begin(), cmpr.end(), cmp);
	vector<int> sum(n);
	long long res = 0;
	for(auto i = 0; i < n; ++ i){
		int p = lower_bound(cmpr.begin(), cmpr.end(), a[i], cmp) - cmpr.begin();
		res += i;
		for(auto r = p + !count_equal; r > 0; r -= r & -r) res -= sum[r - 1];
		for(++ p; p <= n; p += p & -p) ++ sum[p - 1];
	}
	return res;
}

// DEBUG BEGIN
#ifdef LOCAL
// DECLARATION BEGIN
template<class L, class R> ostream &operator<<(ostream &out, const pair<L, R> &p);
template<class Tuple, size_t N> struct _tuple_printer;
template<class... Args> ostream &_print_tuple(ostream &out, const tuple<Args...> &t);
template<class ...Args> ostream &operator<<(ostream &out, const tuple<Args...> &t);
template<class T> ostream &operator<<(class enable_if<!is_same<T, string>::value, ostream>::type &out, const T &arr);
ostream &operator<<(ostream &out, const _Bit_reference &bit);
template<size_t SZ> ostream &operator<<(ostream &out, const bitset<SZ> &b);
template<class T, class A, class C>
ostream &operator<<(ostream &out, priority_queue<T, A, C> pq);
// DECLARATION END
template<class L, class R> ostream &operator<<(ostream &out, const pair<L, R> &p){
	return out << "{" << p.first << ", " << p.second << "}";
}
template<class Tuple, size_t N> struct _tuple_printer{
	static ostream &_print(ostream &out, const Tuple &t){ return _tuple_printer<Tuple, N-1>::_print(out, t) << ", " << get<N-1>(t); }
};
template<class Tuple> struct _tuple_printer<Tuple, 1>{
	static ostream &_print(ostream &out, const Tuple& t){ return out << get<0>(t); }
};
template<class... Args> ostream &_print_tuple(ostream &out, const tuple<Args...> &t){
	return _tuple_printer<decltype(t), sizeof...(Args)>::_print(out << "{", t) << "}";
}
template<class ...Args> ostream &operator<<(ostream &out, const tuple<Args...> &t){
	return _print_tuple(out, t);
}
template<class T> ostream &operator<<(class enable_if<!is_same<T, string>::value, ostream>::type &out, const T &arr){
	if(arr.empty()) return out << "{}";
	out << "{";
	for(auto it = arr.begin(); it != arr.end(); ++ it){
		out << *it;
		next(it) != arr.end() ? out << ", " : out << "}";
	}
	return out;
}
ostream &operator<<(ostream &out, const _Bit_reference &bit){
	return out << bool(bit);
}
template<size_t SZ> ostream &operator<<(ostream &out, const bitset<SZ> &b){
	for(auto i = 0; i < SZ; ++ i) out << b[i];
	return out;
}
template<class T, class A, class C>
ostream &operator<<(ostream &out, priority_queue<T, A, C> pq){
	vector<T> a;
	while(!pq.empty()) a.push_back(pq.top()), pq.pop();
	return out << a;
}
template<class Head>
void debug_out(Head H){ cerr << H << endl; }
template<class Head, class... Tail>
void debug_out(Head H, Tail... T){ cerr << H << ", ", debug_out(T...); }
void debug2_out(){ }
template<class Head, class... Tail>
void debug2_out(Head H, Tail... T){ cerr << "\n"; for(auto x: H) cerr << x << ",\n"; debug2_out(T...); }
template<class Width, class Head>
void debugbin_out(Width w, Head H){
	for(auto rep = w; rep; -- rep, H >>= 1) cerr << (H & 1);
	cerr << endl;
}
template<class Width, class Head, class... Tail>
void debugbin_out(Width w, Head H, Tail... T){
	for(auto rep = w; rep; -- rep, H >>= 1) cerr << (H & 1);
	cerr << ", "; debugbin_out(w, T...);
}
enum CODE{ CCRED = 31, CCGREEN = 32, CCYELLOW = 33, CCBLUE = 34, CCDEFAULT = 39 };
#define debug_endl() cerr << endl
#define debug(...) cerr << "\033[" << (int)CODE(CCRED) << "mL" << setw(3) << std::left << __LINE__ << std::right << " [" << #__VA_ARGS__ << "] \033[" << (int)CODE(CCBLUE) << "m", debug_out(__VA_ARGS__), cerr << "\33[" << (int)CODE(CCDEFAULT) << "m"
#define debug2(...) cerr << "\033[" << (int)CODE(CCRED) << "mL" << setw(3) << std::left << __LINE__ << std::right << " [" << #__VA_ARGS__ << "] \033[" << (int)CODE(CCBLUE) << "m", debug2_out(__VA_ARGS__), cerr << "\33[" << (int)CODE(CCDEFAULT) << "m"
#define debugbin(...) cerr << "\033[" << (int)CODE(CCRED) << "mL" << setw(3) << std::left << __LINE__ << std::right << " [" << #__VA_ARGS__ << "] \033[" << (int)CODE(CCBLUE) << "m", debugbin_out(__VA_ARGS__), cerr << "\33[" << (int)CODE(CCDEFAULT) << "m"
#else
#define debug_endl() 42
#define debug(...) 42
#define debug2(...) 42
#define debugbin(...) 42
#endif
// DEBUG END

template<bool Enable_small_to_large = true>
struct disjoint_set{
	int n, _group_count;
	vector<int> p;
	vector<list<int>> group;
	disjoint_set(){ }
	disjoint_set(int n): n(n), _group_count(n), p(n, -1), group(n){ assert(n >= 0);
		for(auto i = 0; i < n; ++ i) group[i] = {i};
	}
	int make_set(){
		p.push_back(-1);
		group.push_back(list<int>{p});
		++ _group_count;
		return n ++;
	}
	int root(int u){
		return p[u] < 0 ? u : p[u] = root(p[u]);
	}
	bool share(int a, int b){
		return root(a) == root(b);
	}
	int size(int u){
		return -p[root(u)];
	}
	bool merge(int u, int v){
		u = root(u), v = root(v);
		if(u == v) return false;
		-- _group_count;
		if constexpr(Enable_small_to_large) if(p[u] > p[v]) swap(u, v);
		p[u] += p[v], p[v] = u;
		group[u].splice(group[u].end(), group[v]);
		return true;
	}
	bool merge(int u, int v, auto act){
		u = root(u), v = root(v);
		if(u == v) return false;
		-- _group_count;
		bool swapped = false;
		if constexpr(Enable_small_to_large) if(p[u] > p[v]) swap(u, v), swapped = true;
		p[u] += p[v], p[v] = u;
		group[u].splice(group[u].end(), group[v]);
		act(u, v, swapped);
		return true;
	}
	int group_count() const{
		return _group_count;
	}
	const list<int> &group_of(int u){
		return group[root(u)];
	}
	vector<vector<int>> group_up(){
		vector<vector<int>> g(n);
		for(auto i = 0; i < n; ++ i) g[root(i)].push_back(i);
		g.erase(remove_if(g.begin(), g.end(), [&](auto &s){ return s.empty(); }), g.end());
		return g;
	}
	void clear(){
		_group_count = n;
		fill(p.begin(), p.end(), -1);
		for(auto i = 0; i < n; ++ i) group[i] = {i};
	}
	friend ostream &operator<<(ostream &out, disjoint_set dsu){
		auto gs = dsu.group_up();
		out << "{";
		if(!gs.empty()) for(auto i = 0; i < (int)gs.size(); ++ i){
			out << "{";
			for(auto j = 0; j < (int)gs[i].size(); ++ j){
				out << gs[i][j];
				if(j + 1 < (int)gs[i].size()) out << ", ";
			}
			out << "}";
			if(i + 1 < (int)gs.size()) out << ", ";
		}
		return out << "}";
	}
};

int main(){
	cin.tie(0)->sync_with_stdio(0);
	cin.exceptions(ios::badbit | ios::failbit);
	modular::precalc_inverse(10'000);
	int n, k;
	cin >> n >> k;
	vector p(k, vector<int>(n));
	disjoint_set dsu(n);
	for(auto i = 0; i < k; ++ i){
		for(auto j = 0; j < n; ++ j){
			cin >> p[i][j], -- p[i][j];
			dsu.merge(j, p[i][j]);
		}
	}
	auto groups = dsu.group_up();
	vector<int> is_cyclic((int)groups.size());
	vector<vector<int>> cycle_gen((int)groups.size());
	vector<vector<int>> compress((int)groups.size(), vector<int>(n));
	vector<vector<int>> cycle_pos((int)groups.size(), vector<int>(n));
	modular res = 0;
	for(auto gi = 0; gi < (int)groups.size(); ++ gi){
		const auto &g = groups[gi];
		int m = (int)g.size();
		debug(g);
		for(auto id = 0; id < m; ++ id){
			compress[gi][g[id]] = id;
		}
		static vector<vector<int>> cur;
		cur.assign(k, vector<int>(m));
		for(auto i = 0; i < k; ++ i){
			for(auto id = 0; id < m; ++ id){
				cur[i][id] = compress[gi][p[i][g[id]]];
			}
		}
		debug2(cur);
		int base = -1;
		for(auto i = 0; i < (int)cur.size(); ++ i){
			static vector<int> vis;
			vis.assign(m, false);
			for(auto rep = (int)g.size(), j = 0; rep; -- rep){
				vis[j] = true;
				j = cur[i][j];
			}
			if(ranges::all_of(vis, identity())){
				base = i;
				break;
			}
		}
		debug(base);
		if(~base){
			static vector<vector<int>> gen;
			gen = {vector<int>(m)};
			iota(gen[0].begin(), gen[0].end(), 0);
			for(auto rep = m - 1; rep; -- rep){
				static vector<int> a;
				a.assign(m, -1);
				for(auto j = 0; j < m; ++ j){
					a[j] = gen.back()[cur[base][j]];
				}
				gen.push_back(a);
			}
			ranges::sort(gen);
			debug2(gen);
			for(auto a: cur){
				if(!ranges::binary_search(gen, a)){
					goto FAIL;
				}
			}
			{
				is_cyclic[gi] = true;
				for(auto rep = m, j = g[0]; rep; -- rep){
					cycle_pos[gi][j] = (int)cycle_gen[gi].size();
					cycle_gen[gi].push_back(j);
					j = p[base][j];
				}
				modular sum = 0;
				for(auto a: gen){
					sum += modular(count_inversions(a));
				}
				debug("normal sum", sum);
				res += sum / m;
			}
			debug_endl();
			continue;
		}
		FAIL:;
		debug("failed");
		res += modular(m) * (m - 1) / 4;
		debug_endl();
	}
	debug2(groups);
	debug(res);
	debug(is_cyclic);
	debug2(cycle_gen);
	debug_endl();
	for(auto gi = 0; gi < (int)groups.size(); ++ gi){
		const auto &g = groups[gi];
		for(auto gj = gi + 1; gj < (int)groups.size(); ++ gj){
			const auto &h = groups[gj];
			if(!is_cyclic[gi] || !is_cyclic[gj]){
				array<int, 2> cnt{};
				for(auto j0: g){
					for(auto j1: h){
						++ cnt[j0 < j1];
					}
				}
				modular ratio = modular(cnt[0]) / (cnt[0] + cnt[1]);
				res += modular(cnt[0]) * (1 - ratio) + modular(cnt[1]) * ratio;
				continue;
			}
			int length = gcd((int)g.size(), (int)h.size());
			for(auto i = 0; i < k; ++ i){
				length = gcd(length, abs(cycle_pos[gi][p[i][g[0]]] - cycle_pos[gj][p[i][h[0]]]));
			}
			debug(length);
			vector<array<int, 2>> cnt_index(length), cnt_value(length);
			for(auto li = 0; li < length; ++ li){
				for(auto lj = 0; lj < length; ++ lj){
					int update = (li - lj + length) % length;
					for(auto s = li; s < (int)cycle_gen[gi].size(); s += length){
						int ns = s == (int)cycle_gen[gi].size() - 1 ? 0 : s + 1;
						for(auto t = lj; t < (int)cycle_gen[gj].size(); t += length){
							int nt = t == (int)cycle_gen[gj].size() - 1 ? 0 : t + 1;
							++ cnt_index[update][cycle_gen[gi][s] < cycle_gen[gj][t]];
							++ cnt_value[update][cycle_gen[gi][ns] < cycle_gen[gj][nt]];
						}
					}
				}
			}
			debug(cnt_index);
			debug(cnt_value);
			for(auto dif = 0; dif < length; ++ dif){
				modular ratio = modular(cnt_value[dif][0]) / (cnt_value[dif][0] + cnt_value[dif][1]);
				res += modular(cnt_index[dif][0]) * (1 - ratio) + modular(cnt_index[dif][1]) * ratio;
			}
		}
	}
	cout << res << "\n";
	return 0;
}

/*

*/