Symmetric Matrix Gym - 247727B

Symmetric Matrix Gym - 247727B

Count the number of n×n matrices A satisfying the following condition modulo m.

  • Ai,j∈{0,1,2} for all 1≤i,j≤n.

  • Ai,j=Aj,i for all 1≤i,j≤n.

  • Ai,1+Ai,2+⋯+Ai,n=2 for all 1≤i≤n.

  • A1,1=A2,2=⋯=An,n=0.

Input
The input consists of several test cases and is terminated by end-of-file.

Each test case contains two integers n and m.

  • 1≤n≤105
  • 1≤m≤109
  • The sum of n does not exceed 107.

Output
For each test case, print an integer which denotes the result.

Input
3 1000000000
100000 1000000000
Output
1
507109376

求滿足以上條件的矩陣有多少個

  • 可以把這個矩陣看做一個無向圖的鄰接矩陣,每個點的度都爲2,而且可以有重邊,沒有自環,這就意味着,每個點屬於且僅屬於一個環(也會存在兩個點,兩條邊組成的環),這個問題就可以轉化成了計算滿足這些條件的圖的個數
  • 可以用遞推來計算,F[n]代表n個點的答案
  • F[1] = 0,F[2] = 1,F[3] = 1
  • 當有n個點的時候,第n個點可以拿之前n-1個點中的一個與自己組環,個數是(n-1)*F[n-2]
  • 當從前n-1個點中留下k個點,也就是取n-k-1個點與第n個點組成環的時候,種數是C(n-1,k) * F[k] *(n-k)!/(n-k)/2 =C(n-1,k) * F[k] *(n-k-1)!/2 (ps:m個點的循環全排列的個數是m!/m = (m-1)!,因爲環54321和12345在鄰接矩陣中的表現形式一樣,所以結果除2)
  • 所以F[n] = (n-1)* F[n-2]+(k from 0 to n-3):C(n-1,k) * F[k] *(n-k-1)!/2,然後要通過公式化簡轉化爲遞推式
  • 在這裏插入圖片描述
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+9;
long long f[maxn];
int main()
{
    long long i,j,mod,n;
    while(scanf("%lld %lld",&n,&mod)!=EOF)
    {
        f[1]=0;
        f[2] =1;
        f[3] = 1;
        for(i = 4;i<=n;i++)
        {
            f[i] = ((i-1)*f[i-1]%mod+(i-1)*f[i-2]%mod-(i-1)*(i-2)/2*f[i-3]%mod+mod)%mod;
        }
        cout<<f[n]<<endl;
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章