P4778 Counting Swaps solution to a problem

Combination in the strict sense of the first channel A count off topic, especially to commemorate the first serve.
First real exposure to this type of problem, people feel as if thinking very divergent job ......


For a permutation \ (P_1, P_2, \ DOTS, P_n \) , for each \ (I \) to \ (P_i \) connected one side, can be found throughout FIG constitute a plurality of rings, the goal is to these rings become self-ring.
Lemma: The length \ (n-\) cycloalkyl becomes \ (n-\) a ring from a minimum number of switching \ (. 1-n-\) .
By induction certificate, for the current situation, at any one time will exchange their split in two rings, set up by the knockout law known lemma.
Note \ (F_n \) represents the switching frequency and at least the length \ (n-\) cycloalkyl becomes \ (n-\) a self-loop, how many exchange. From the foregoing, we have to split each into two rings, two rings may wish to set length \ (X, Y \) , and note \ (T (x, y) \) represents the number of different methods of the length of a \ (n-\) loop length becomes \ (x, y \) of the two rings, then when \ (n-\) is even and \ (x = y \) when there \ (T ( X, Y) = \ FRAC {n-2}} {\) , otherwise\ (T (X, Y) = n-\) . Because (X \) \ ring (Y \) \ operation of interfering rings, both sides of the operation may be arranged randomly, and therefore, this is a full array of multiple sets.
So with the recursive expressions: \ [F_n = \ sum_ {} n-X + Y = \ left (T (X, Y) F_xF_y \ FRAC {(2-n-)!} {(X-. 1) (Y-! ! 1)} \ right) \ ] for the title all \ (K \) ring, remember their length \ (\ {L_K \} \) , the final answer is: \ [\ Prod ^ {K} _ {i = 1} F_ {l_ {i}} \ dfrac {(nk)!} {\ prod ^ {k} _ {i = 1} (l_i-1)!} \] not finished,After the baptism JOJOFound \ (F_n = n-2-n-^ {} \) ! Immediately reduced complexity \ (O (n-\ log n-) \) ......
(Sao find this loop operation is learned as a solution to a problem region dalao only orz

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

const int N=1e5+5;
const ll mod=1e9+9;
int n,a[N],L[N],cnt;
ll fac[N]={1,1},F[N]={0,1};
bool vis[N];

ll qpow(ll bas,ll p)
{
    ll res=1; bas%=mod;
    for(;p;p>>=1)
    {
        if(p&1) res=res*bas%mod;
        bas=bas*bas%mod;
    }
    return res;
}

int dfs(int x)
{
    vis[x]=1;
    if(vis[a[x]]) return 1;
    return dfs(a[x])+1;
}

int main()
{
    int T; scanf("%d",&T);
    for(int i=2;i<N;++i)
        fac[i]=i*fac[i-1]%mod,
        F[i]=qpow(i,i-2)%mod;
    while(T--)
    {
        memset(vis,0,sizeof(vis));
        cnt=0;
        scanf("%d",&n);
        for(int i=1;i<=n;++i)
            scanf("%d",&a[i]);
        for(int i=1;i<=n;++i)
            if(!vis[i]) L[++cnt]=dfs(i);
        ll ans=fac[n-cnt];
        for(int i=1;i<=cnt;++i)
            ans=ans*F[L[i]]%mod*qpow(fac[L[i]-1],mod-2)%mod;
        printf("%lld\n",ans);
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/wzzyr24/p/12234527.html