FZU 1627 Revival's road【DP(矩阵快速幂)】

本文介绍了一种使用图论和动态规划结合快速幂的方法来解决特定路径计数问题。该问题是在给定的有向图中寻找从起点到终点经过指定步数的所有可能路径数量。文章详细解释了算法原理,并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Oaiei is idle, and recently he wants to travel around the country. In his country there are N cities, they are numbered from 1 to N. There are roads between some cities, but some are not directly connected with each other. Oaiei lives in the city 1, and he wants to go to city N. Now, he has a question. In k steps, he would like to know there are how many ways from city 1 to city N. You should note that althought there is a road between city A and city B, there is not necessarily a road between city B and city A.

Input
There are multiple tests. For each test, the first line contains three integers N、M and k(2<=N<=100,1<=M<=N*N,1<=k<=10^9), N denotes the number of cities, M denotes the number of roads between the N cities. Following M lines, each line contains two integers A and B, denoting there is a road between city A and city B.

Output
There are how many ways from city 1 to city N. Becase the answer can be very large, you should output the answer MOD 10000.

Sample Input
4 5 9
1 2
2 3
3 4
4 1
1 3
4 5 1
1 2
2 3
3 4
4 1
1 3
Sample Output
3
0

题意:给你M条有向边,总共需要走K步,求1走到N的方案数。

这是一道图论的动态规划求方案数的问题,可以用矩阵的计算进行优化,对于矩阵再用快速幂。

分析:每一次矩阵乘法 相当于对每个点累积了一下从别的点走过来的和
感觉这种思路十分巧妙。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1e2 + 5;
int N, M, K;
int a[105][105];
int tmp[maxn][maxn];
int res[maxn][maxn];
const int mod = 10000;
void multi(int a[][maxn], int b[][maxn], int n)
{
    memset(tmp, 0, sizeof tmp);
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            for (int k = 1; k <= n; k++)
            {
                (tmp[i][j] += a[i][k] * b[k][j])%=mod;
            }
        }
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            (a[i][j] = tmp[i][j])%=mod;
        }
    }
}
void pow_multi(int a[][maxn], int n)
{
    memset(res, 0, sizeof res);
    for (int i = 1; i <= N; i++)//dwjz
    {
        res[i][i] = 1;
    }
    while (n)
    {
        if (n & 1)
        {
            multi(res, a, N);
        }
        multi(a, a, N);
        n >>= 1;
    }
}
int main()
{
    while (~scanf("%d%d%d", &N, &M, &K))
    {
        memset(a, 0, sizeof a);

        for (int i = 0; i < M; i++)
        {
            int u, v;
            scanf("%d%d", &u, &v);
            a[u][v] = 1;
            //a[v][u] = 1;
        }
        pow_multi(a, K);
        printf("%d\n", res[1][N]);
        //printf("%d\n", res[N][1]);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值