WOJ 26 Lost in WHU(矩阵快速幂+邻接矩阵乘法)

来源:互联网 发布:exescope是什么软件 编辑:程序博客网 时间:2024/06/14 23:31

Input file: standard inputOutput file: standard output Time limit: 1 secondMemory 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≤100N100) and the number of edges MM (M≤N(N−1)/2MN(N1)/2).

The ii-th line of next MM lines contains two numbers uiui and vivi, which respents an edge (ui,vi)(ui,vi).

The last line contains the deadline TT(T≤109T109).

Output

The number of plan to reach the destination by deadline module 109+7109+7.

Examples

Input 1

4 51 32 33 41 21 48

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;}


0 0
原创粉丝点击