【矩阵 && A 点到 B 点走 K 步的路径条数(可以走重复边) 】HDU - 2157 How many ways??

Step1 Problem:

给你 n 个点,m 条边的图(有向),T 次询问,对于每次询问你 A 点到 B 点走K步的路径条数(可以走重复边)。
数据范围:
0 < n <= 20, m <= 100, 1 <= T <= 100

Step2 Ideas:

我们知道 a->k 路径数 x,k->b 路径数 y,a->k->b 的路径数 x*y。

Step3 Code:

#include<bits/stdc++.h>
using namespace std;
const int N = 25;
const int mod = 1000;
struct node
{
    int a[N][N];
};
node c, ans;
int n;
node mul(node x, node y)
{
    node ans;
    memset(ans.a, 0, sizeof(ans.a));
    for(int k = 0; k < n; k++)
    {
        for(int i = 0; i < n; i++)
        {
            if(x.a[i][k])
            for(int j = 0; j < n; j++)
            {
                ans.a[i][j] += x.a[i][k]*y.a[k][j];
                ans.a[i][j] %= mod;
            }
        }
    }
    return ans;
}
node Pow(node x, int m)
{
    node ans;
    memset(ans.a, 0, sizeof(ans.a));
    for(int i = 0; i < n; i++) ans.a[i][i] = 1;
    while(m)
    {
        if(m&1) ans = mul(ans, x);
        x = mul(x, x);
        m >>= 1;
    }
    return ans;
}
int main()
{
    int m, u, v, step;
    while(~scanf("%d %d", &n, &m) && (n||m))
    {
        memset(c.a, 0, sizeof(c.a));
        while(m--)
        {
            scanf("%d %d", &u, &v);
            c.a[u][v] = 1;
        }
        scanf("%d", &m);
        while(m--)
        {
            scanf("%d %d %d", &u, &v, &step);
            ans = Pow(c, step);
            printf("%d\n", ans.a[u][v]);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值