牛客网暑期ACM多校训练营(第一场)B Symmetric Matrix

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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值