#include<bits/stdc++.h> using namespace std; typedef long double ld; typedef long long ll; #define rep(a, b) for(int a = 0; a < (b); ++a) #define st first #define nd second #define pb push_back #define all(a) a.begin(), a.end() const ll MOD=1e9+7; const int LIM=3e3+7; ll T[LIM][LIM], F[LIM*LIM], ile[LIM*LIM], inv[LIM*LIM]; ll pot(ll a, ll b) { ll ans=1; while(b) { if(b&1) ans=(ans*a)%MOD; a=(a*a)%MOD; b/=2; } return ans; } int fnd(int x) { if(F[x]==x) return x; return F[x]=fnd(F[x]); } void uni(int a, int b) { if(fnd(a)==fnd(b)) return; ile[fnd(a)]+=ile[fnd(b)]; inv[fnd(a)]+=inv[fnd(b)]; F[fnd(b)]=fnd(a); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, k; cin >> n >> k; rep(i, k) { rep(j, n) { cin >> T[i][j]; --T[i][j]; } } rep(i, n*n) { F[i]=i; ile[i]=1; } rep(a, n) rep(b, n) if(a>b) inv[a*n+b]=1; rep(i, k) { rep(b, n) rep(a, n) uni(a*n+b, T[i][a]*n+T[i][b]); } ll ans=0; rep(a, n) rep(b, n) if(a<b) ans=(ans+inv[fnd(a*n+b)]*pot(ile[fnd(a*n+b)], MOD-2))%MOD; cout << ans << '\n'; }
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 | #include<bits/stdc++.h> using namespace std; typedef long double ld; typedef long long ll; #define rep(a, b) for(int a = 0; a < (b); ++a) #define st first #define nd second #define pb push_back #define all(a) a.begin(), a.end() const ll MOD=1e9+7; const int LIM=3e3+7; ll T[LIM][LIM], F[LIM*LIM], ile[LIM*LIM], inv[LIM*LIM]; ll pot(ll a, ll b) { ll ans=1; while(b) { if(b&1) ans=(ans*a)%MOD; a=(a*a)%MOD; b/=2; } return ans; } int fnd(int x) { if(F[x]==x) return x; return F[x]=fnd(F[x]); } void uni(int a, int b) { if(fnd(a)==fnd(b)) return; ile[fnd(a)]+=ile[fnd(b)]; inv[fnd(a)]+=inv[fnd(b)]; F[fnd(b)]=fnd(a); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, k; cin >> n >> k; rep(i, k) { rep(j, n) { cin >> T[i][j]; --T[i][j]; } } rep(i, n*n) { F[i]=i; ile[i]=1; } rep(a, n) rep(b, n) if(a>b) inv[a*n+b]=1; rep(i, k) { rep(b, n) rep(a, n) uni(a*n+b, T[i][a]*n+T[i][b]); } ll ans=0; rep(a, n) rep(b, n) if(a<b) ans=(ans+inv[fnd(a*n+b)]*pot(ile[fnd(a*n+b)], MOD-2))%MOD; cout << ans << '\n'; } |