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
#include<bits/stdc++.h>
using namespace std;

#define ll int64_t
#define pb push_back
#define pii pair<int, int>
#define st first
#define nd second
#define sz(x) (int)(x).size()
#define all(x) (x).begin(), (x).end()

const int MOD = 1e9+7;
int F(int a, int b) {
	int c = 1;
	while(b) {
		if(b%2)
			c = 1LL*c*a%MOD; 
		a = 1LL*a*a%MOD;
		b/=2;
	}
	return c;
}

const int MAXN = 1<<24;

int p[MAXN];
vector<int> V[MAXN];
int goal;

bool Union(int x, int y) {
	x = p[x], y = p[y];
	if(sz(V[x])<sz(V[y])) swap(x, y);
	for(int a:V[y]) {
		p[a] = x;
		V[x].pb(a);
	}
	V[y].clear();
	V[y].shrink_to_fit();
	if(sz(V[x])==goal) return true;
	return false;
}

int32_t main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	int n, k;
	cin >> n >> k;
	goal = n*(n-1);
	for(int i=0;i<n;i++) {
		for(int j=0;j<n;j++) {
			p[i<<12|j] = {i<<12|j};
			V[i<<12|j] = {i<<12|j};
		}
	}
	for(int i=0;i<k;i++) {
		vector<int> v(n);
		for(int j=0;j<n;j++) {
			cin >> v[j], v[j]--;
		}
		for(int a=0;a<n;a++) {
			for(int b=0;b<n;b++) {
				if(a!=b&&p[a<<12|b]!=p[v[a]<<12|v[b]]) {
					if(Union(a<<12|b, v[a]<<12|v[b])) {
						goto skip;
					}
				}
			}
		}
	}
skip:
	ll ans = 0;
	int mask = (1<<12)-1;
	for(int i=0;i<n;i++) {
		for(int j=0;j<n;j++) {
			if(i==j) continue;
			int c1=0, c2=0;
			for(int x:V[i<<12|j]) {
				if((x>>12)<(x&mask)) c1++;
				if((x>>12)>(x&mask)) c2++;
			}
			ans = (ans+1LL*c1*c2%MOD*F(c1+c2, MOD-2))%MOD;
		}
	}
	cout << ans << "\n";
}