路径数量 dp 思维题

链接: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-2-4

第二条路径:1-3-4

思路:dp[n][k]表示走k步到达第n个点有dp[n][k]种方法

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#include<vector>
#include<set>
#include<cstdlib>
#include<map>
#include<deque>
#include<queue>
#include<list>
const int inf=0x3f3f3f3f;
const int MOD=1e9+7;
const int inff=999999;
const int N=1005;
const int M=2005;
#define LL long long
#define ME0(x) memset(x,0,sizeof(x))
#define MEF(x) memset(x,-1,sizeof(x))
#define MEI(x) memset(x,inf,sizeof(x))
using namespace std;
LL n,k,mapt[35][35],ans[35][15];
int main()
{
    cin>>n>>k;
    for(int n1=1;n1<=n;n1++)
    {
        for(int n2=1;n2<=n;n2++)
        {
            cin>>mapt[n1][n2];
        }
    }
    ME0(ans);
    ans[1][0]=1;
    for(int i=1;i<=k;i++)
    {
        for(int j=1;j<=n;j++)
        {
            for(int a=1;a<=n;a++)
            {
                if(mapt[a][j])
                {
                    ans[j][i]=ans[j][i]+ans[a][i-1];
                }
            }
        }
    }
    cout<<ans[n][k]<<endl;
}

猜你喜欢

转载自blog.csdn.net/ecjtu_17_TY/article/details/82694609