#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll MOD = 1e9+7; const int N = 3007; ll binpow(ll x,int power){ ll mult = x%MOD; x = 1; while(power){ if (power&1){ x = x*mult%MOD; } mult = mult*mult%MOD; power /= 2; } return x; } struct dsu{ int P[N*N],Sum[N*N],Sz[N*N]; void init(int n){ for(int i = 0;i<n;i+=1){ for(int j = 0;j<n;j+=1){ P[i*n+j] = i*n+j; Sz[i*n+j] = 1; Sum[i*n+j] = int(i>j); } } } int F(int x){ if (x==P[x]){ return x; } return P[x] = F(P[x]); } void unite(int a,int b){ a = F(a); b = F(b); if (a==b){ return; } Sz[b] += Sz[a]; Sum[b] += Sum[a]; P[a] = b; } int get_sum(int x){ return Sum[F(x)]; } int get_sz(int x){ return Sz[F(x)]; } } D; int P[N]; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int n,k; cin>>n>>k; D.init(n); for(int s = 0;s<k;s+=1){ for(int i = 0;i<n;i+=1){ cin>>P[i]; P[i] -= 1; } for(int i = 0;i<n;i+=1){ for(int j = 0;j<n;j+=1){ D.unite(i*n+j,P[i]*n+P[j]); } } } ll ans = 0; for(int i = 0;i<n;i+=1){ for(int j = i+1;j<n;j+=1){ ans += D.get_sum(i*n+j)*binpow(D.get_sz(i*n+j),MOD-2); ans %= 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 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 | #include <bits/stdc++.h> using namespace std; typedef long long ll; const ll MOD = 1e9+7; const int N = 3007; ll binpow(ll x,int power){ ll mult = x%MOD; x = 1; while(power){ if (power&1){ x = x*mult%MOD; } mult = mult*mult%MOD; power /= 2; } return x; } struct dsu{ int P[N*N],Sum[N*N],Sz[N*N]; void init(int n){ for(int i = 0;i<n;i+=1){ for(int j = 0;j<n;j+=1){ P[i*n+j] = i*n+j; Sz[i*n+j] = 1; Sum[i*n+j] = int(i>j); } } } int F(int x){ if (x==P[x]){ return x; } return P[x] = F(P[x]); } void unite(int a,int b){ a = F(a); b = F(b); if (a==b){ return; } Sz[b] += Sz[a]; Sum[b] += Sum[a]; P[a] = b; } int get_sum(int x){ return Sum[F(x)]; } int get_sz(int x){ return Sz[F(x)]; } } D; int P[N]; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int n,k; cin>>n>>k; D.init(n); for(int s = 0;s<k;s+=1){ for(int i = 0;i<n;i+=1){ cin>>P[i]; P[i] -= 1; } for(int i = 0;i<n;i+=1){ for(int j = 0;j<n;j+=1){ D.unite(i*n+j,P[i]*n+P[j]); } } } ll ans = 0; for(int i = 0;i<n;i+=1){ for(int j = i+1;j<n;j+=1){ ans += D.get_sum(i*n+j)*binpow(D.get_sz(i*n+j),MOD-2); ans %= MOD; } } cout<<ans<<'\n'; } |