牛客OI赛制测试赛2 B题

链接:https://www.nowcoder.com/acm/contest/185/B
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述
给出一个 n * n 的邻接矩阵A.
A是一个01矩阵 .
A[i][j]=1表示i号点和j号点之间有长度为1的边直接相连.
求出从 1 号点 到 n 号点长度为k的路径的数目.

输入描述:
第1行两个数n,k (20 ≤n ≤ 30,1 ≤ k ≤ 10)
第2行至第n+1行,为一个邻接矩阵

输出描述:
题目中所求的数目

示例1

输入
4 2
0 1 1 0
1 0 0 1
1 0 0 1
0 1 1 0

输出
2

/*
思路1:矩阵连乘k次,a[1][N]即为答案(离散书上的定理,复杂度O(k*n³))
思路2:dp 复杂度O(n³)如下
*/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>

#define INF 0x3f3f3f3
using namespace std;
typedef long long LL;
const int maxn=35;
LL a[maxn][maxn],dp[maxn][maxn];
int N,k;

int main()
{
    scanf("%d%d",&N,&k);
    for(int i=1;i<=N;i++)
        for(int j=1;j<=N;j++)
            scanf("%lld",&a[i][j]);
    dp[1][0]=1;
    for(int t=1;t<=N;t++)
    {
        for(int i=1;i<=N;i++)
        {
            for(int j=1;j<=N;j++)
                if(a[i][j])
                dp[j][t]+=dp[i][t-1];
        }
    }
    printf("%lld\n",dp[N][k]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41646772/article/details/82495269