标题 26. Lost in WHU
Input file: standard input
Output file: standard output
Time limit: 1 second
Memory limit: 512 mebibytesAs 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.Input 1
4 5
1 3
2 3
3 4
1 2
1 4
8
Output 1
170
题目大意:有n个点,m条边,每条边代表这条路能走,有k时间。
问:从1到n,有多少种走法;
思路 1:可以往回走,只要没有到达n和时间没有结束;
2:到达n后不能再走了,即使时间未到;
3:时间未到时,到达n,也算一次;
#include<stdio.h>
#define mod 1000000007
struct mat
{
long long a[110][110];
};
mat I;
int n;
mat mat_mul(mat q,mat w)
{
int i,j;
mat A;
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
A.a[i][j]=0;
for(int k=1; k<=n; k++)
{
A.a[i][j]+=(q.a[i][k]*w.a[k][j])%mod;//结构体,要开long long,乘的时候会爆表;
A.a[i][j]%=mod;
}
}
}
return A;
}
mat mul(mat q,long long k)
{
mat sum;
for(int i=1; i<n; i++)//初始化,单位矩阵;
sum.a[i][i]=1;
mat c=q;
while(k)
{
if(k&1)
sum=mat_mul(sum,c);
c=mat_mul(c,c);
k>>=1;
}
return sum;
}
int main()
{
int m;
long long k;
while(~scanf("%d%d",&n,&m))
{
mat map,ans;
int i,j;
for(i=0; i<m; i++)
{
int x,y;
scanf("%d%d",&x,&y);
if(x!=n) map.a[x][y]=1;//保证到达n时,不再走了;
if(y!=n) map.a[y][x]=1;
}
map.a[n][n]=1;//重点;
//关键:与一般矩阵快速幂不同,这一步可以加上时间未到,但到达n 的也可以加起来;
//一般的矩阵快速幂是到n时恰好是k步的有多少步;
scanf("%I64d",&k);
ans=mul(map,k);
printf("%I64d\n",ans.a[1][n]);
}
return 0;
}