B Symmetric Matrix
链接:https://www.nowcoder.com/acm/contest/139/B
来源:牛客网
时间限制: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;
}