题目
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=A∗A ,那么 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;
}