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 N 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 N).
Input
First line contains the number of points N (N≤100) and the number of edges M (M≤N(N−1)/2).
The i-th line of next M lines contains two numbers ui and vi, which respents an edge (ui,vi).
The last line contains the deadline T(T≤109).
Output
The number of plan to reach the destination by deadline module 109+7.
Examples
Input 1
4 5
1 3
2 3
3 4
1 2
1 4
8
Output 1
170
题目大意:
给一个图,求从点1到点N不超过K步的路径数。
解题思路:
首先,非常明确求图上走K步的路径数的解法为临界矩阵乘法,由于题目步数非常大,所以我们用矩阵快速幂即可。不过这题有两个还需要考虑两个细节:第一,人走到终点后就不会再走了,所以我们在建邻接矩阵的时候必须把与终点连接的边设为单向边。第二,题目求的是不超过K步的方案数,但是直接用乘法得到的是恰好K步的方案数,所以我们需要给终点加一个自环,相当于然提前到达终点的情况一直留在终点,也可以从矩阵乘法的意义解释。
AC代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <cstdlib>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <ctime>
using namespace std;
#define INF 0x3f3f3f3f
#define LL long long
#define fi first
#define se second
#define mem(a,b) memset((a),(b),sizeof(a))
const int MAXN=100+3;
const LL MOD=1000000000+7;
LL N,M,T;
struct Matrix
{
LL a[MAXN][MAXN];//矩阵大小根据需求修改
Matrix()
{
memset(a,0,sizeof(a));
}
void init()
{
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
a[i][j]=(i==j);
}
Matrix operator * (const Matrix &B)const
{
Matrix C;
for(int i=0;i<N;i++)
for(int k=0;k<N;k++)
for(int j=0;j<N;j++)
C.a[i][j]=(C.a[i][j]+1LL*a[i][k]*B.a[k][j])%MOD;
return C;
}
Matrix operator ^ (const LL &t)const
{
Matrix A=(*this),res;
res.init();
LL p=t;
while(p)
{
if(p&1)res=res*A;
A=A*A;
p>>=1;
}
return res;
}
Matrix& operator = (const Matrix &other)
{
for(int i=0;i<=N;++i)
for(int j=0;j<=N;++j)
a[i][j]=other.a[i][j];
return *this;
}
};
int main()
{
while(~scanf("%lld%lld",&N,&M))
{
Matrix G;
for(int i=0;i<M;++i)
{
int u,v;
scanf("%d%d",&u,&v);
if(v==N)//与终点连接的边设为单向
G.a[u-1][v-1]=1;
else if(u==N)
G.a[v-1][u-1]=1;
else G.a[u-1][v-1]=G.a[v-1][u-1]=1;
}
G.a[N-1][N-1]=1;//添加终点的自环
scanf("%lld",&T);
G=G^T;
printf("%lld\n",G.a[0][N-1]);
}
return 0;
}