牛客網暑期ACM多校訓練營(第一場)B Symmetric Matrix
阿新 • • 發佈:2019-02-04
B Symmetric Matrix
時間限制:C/C++ 1秒,其他語言2秒
空間限制:C/C++ 524288K,其他語言1048576K
64bit IO Format: %lld
題目描述
Count the number of n x 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.
輸入描述:
The input consists of several test cases and is terminated by end-of-file.
Each test case contains two integers n and m.
輸出描述:
For each test case, print an integer which denotes the result.
示例1
輸入
3 1000000000
100000 1000000000
輸出
1
507109376
備註:
* 1 ≤ n ≤ 105 * 1 ≤ m ≤ 109 * The sum of n does not exceed 107.
題意:給出一個矩陣 矩陣每行的和必須為2 且是一個沿右對角線(右對角線上的值全為0)對稱的矩陣 問你大小為n的這樣的合法矩陣有多少個。
思路:因為是n*n的矩陣,所以可以認為是一個無向圖的鄰接矩陣,滿足每個點的度必須為2,且可以有重邊(1-2可以連兩次),求合法的圖有多少個?可以想到用dp來求解;
設dp[i]為點數為i時的答案,當新加入一個點時,當前點數為n(包括新加入的點),從舊的點(n-1個)中挑出x個,剩餘的舊點與新點組成一個環,要注意挑的x要大於等於2,且保證(n-1-x)>=2,因為當(n-1-x)>=2時,新點組時環答案會有重複,考慮對稱性需要除2,那麼(n-1-x)=1和x=0需要單獨算:
dp[n]=(n-1)*dp[n-2](x為n-2)+sigma(x:2->n-3)C(n-1,x)*(n-1-x)!*dp[x]/2+(n-1)!/2(x為0)
即dp[n]=(n-1)*dp[n-2]+sigma(x:2->n-3)*dp[x]*(n-1)!/(2*x!)+(n-1)!/2
那麼dp[n-1]=(n-2)*dp[n-3]+sigma(x:2->n-4)*dp[x]*(n-2)!/(2*x!)+(n-2)!/2
即:(n-1)*dp[n-1]=(n-1)*(n-2)*dp[n-3]+sigma(x:2->n-4)*dp[x]*(n-1)!/(2*x!)+(n-1)!/2
dp[n]-(n-1)*dp[n-1]=(n-1)*dp[n-2]-(n-1)*(n-2)*dp[n-3]+dp[n-3]*(n-1)!/(2*(n-3)!)
=(n-1)*dp[n-2]-(n-1)*(n-2)*dp[n-3]+(n-1)*(n-2)*dp[n-3]/2
=(n-1)*dp[n-2]-(n-1)*(n-2)*dp[n-3]/2
dp[n]=(n-1)*dp[n-2]-(n-1)*(n-2)*dp[n-3]/2+(n-1)*dp[n-1]
#include<bits/stdc++.h>
using namespace std;
//FILE *fin, *out;
//fin = fopen("money.fin", "r");
//out = fopen("money.out", "w");
//ofstream fout("money.out");
//ifstream fin("money.in");
long long dp[100005];
int main(){
int n,m;
while(scanf("%d%d",&n,&m)==2){
dp[2]=dp[3]=1;
for(long long i=4;i<=n;i++){
dp[i]=(((i-1)*(dp[i-1]+dp[i-2]))%m-((i-1)*(i-2)/2*dp[i-3])%m+m)%m;
}
printf("%lld\n",dp[n]);
}
return 0;
}