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
#include <iostream>
#include <set>
#include <vector>

#define perm std::vector<int>
constexpr int maxn = 3000, treeSize = 8192, mod = 1e9 + 7;
int n, k;
perm fav[maxn];
long long sum;

std::set<perm> set;

perm operator*(const perm& a, const perm& b) {
    perm res(n);
    for(int i = 1; i < n; i++)
        res[i] = a[b[i]];
    return res;
}

long long fastPow(long long a, int exp) {
    if(exp == 0)
        return 1;
    auto half = fastPow(a, exp / 2);
    return (((half * half) % mod) * (exp % 2 == 0 ? 1 : a)) % mod;
}

void input() {
    scanf("%d%d", &n, &k);
    n++;
    for(int i = 0; i < k; i++) {
        fav[i].resize(n);
        for(int j = 1; j < n; j++)
            scanf("%d", &(fav[i][j]));
    }
}

int tree[treeSize];
void add(int i, int x) {
    i += treeSize / 2;
    while(i) {
        tree[i] += x;
        i /= 2;
    }
}
int query(int l, int r) {
    l += treeSize / 2; r += treeSize / 2;
    int ans = tree[l];
    if(l != r)
        ans += tree[r];
    while(l / 2 != r / 2) {
        if(l % 2 == 0)
            ans += tree[l + 1];
        if(r % 2 == 1)
            ans += tree[r - 1];
        l /= 2; r /= 2;
    }
    return ans;
}

int countInversions(const perm& a) {
    int ans = 0;
    for(const auto& i : a) {
        if(i == a[0])
            continue;
        ans += query(i, n + 1);
        add(i, 1);
    }
    for(const auto& i : a) {
        if(i == a[0])
            continue;
        add(i, -1);
    }
    return ans;
}

void brut(const perm& p) {
    if(set.find(p) != set.end())
        return;
    set.insert(p);
    sum = (sum + countInversions(p)) % mod;
    for(int i = 0; i < k; i++)
        brut(p * fav[i]);
}

int main() {
    input();
    perm start(n);
    for(int i = 1; i < n; i++)
        start[i] = i;
    brut(start);
    long long ans = (sum * fastPow(set.size(), mod - 2)) % mod;
    printf("%lld", ans);
    return 0;
}