WOJ 26. Lost in WHU(矩阵快速幂变形)

题目

Input file: standard input
Output file: standard output
Time limit: 1 second
Memory limit: 512 mebibytes
As one of the most beautiful campus in China, Wuhan University is around several hills, so the road is complex and visitors always lose themselves. Give a undirected graph of WHU of NN points and a deadline, then you should count the number of plan to reach the destination by deadline (the starting point is 1 and the ending point is NN).

Input
First line contains the number of points NN (N\le 100N≤100) and the number of edges MM (M\le N(N-1)/2M≤N(N−1)/2).

The ii-th line of next MM lines contains two numbers u_iu
​i
​​ and v_iv
​i
​​ , which respents an edge (u_i, v_i)(u
​i
​​ ,v
​i
​​ ).

The last line contains the deadline TT(T\le 10^9T≤10
​9
​​ ).

Output
The number of plan to reach the destination by deadline module 10^9+710
​9
​​ +7.

Examples
Input 1
4 5
1 3
2 3
3 4
1 2
1 4
8
Output 1
170

题目分析

这道题就是问你从1到n在T步之内有多少种不同的走法。其实这里面可以利用矩阵相乘进行求解,假设矩阵 C=AA ,那么 c[i][j]=mk=1A[i][k]A[k][j] ,那么很明显这里C[i][j]相当于从i出发走到j经过了2段路的方法数,因此这道题也可以这样求解,但是这道题要求的含T步以内的,因此我们要想方法,如果到达n点之后,那么不能再离开n点了。。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define LL long long
const int maxn = 105;
const LL mod = 1e9+7;

void add(LL& x, LL y){   
    x = (x+y%mod)%mod;
}

struct Matrix{
    int n;
    LL a[maxn][maxn];
    Matrix() {}
    void init(int _n){  //初始化
        n = _n;
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++) a[i][j] = 0;
    }

    void solve(int _n){  //构造成单位矩阵
        n = _n;
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++) a[i][j]=(i==j)?1:0;
    }

    Matrix operator*(const Matrix &t)const{  //重载*运算符
        Matrix ans;
        ans.init(n);
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)
                for(int k = 1; k <= n; k++) add(ans.a[i][j], a[i][k]*t.a[k][j]);
        return ans;
    }
};

Matrix quick_pow(Matrix a, int T){  //快速幂
    Matrix ans;
    ans.solve(a.n);
    while(T){
        if(T&1) ans = ans*a;
        a = a*a;
        T >>= 1;
    }
    return ans;
}

int main(){
    int n, m, T;
    while(scanf("%d%d", &n, &m) != EOF){
        int u, v;
        Matrix x;
        x.init(n);
        for(int i = 0; i < m; i++){
            scanf("%d%d", &u, &v);
            x.a[u][v] = 1;
            x.a[v][u] = 1;
        }
        for(int i = 1; i <= n; i++) x.a[n][i] = 0;
        x.a[n][n] = 1;
        scanf("%d", &T);
        Matrix ans = quick_pow(x, T);
        printf("%lld\n", ans.a[1][n]);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值