题址:https://oj.ejq.me/problem/26
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 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,最多走T步能有多少种情况,到n点就不能再离开n点了。
思路:因为图里有环,所以只要步数够就能一直绕下去,T非常大,暴力肯定不行。
每次记录走j步到每个点的情况有多少种,如果一次走一步,也会超时的,所以用矩阵快速幂。
把输入的东西做成一个矩阵(行走路线)
样例的矩阵为0 1 1 1
1 0 1 0
1 1 0 1
0 0 0 1
第j行 第i竖列 :1代表能到点j能到点i,0代表不能到。
因为走到4就停止,所以4不能走到其他地方。为了把答案存下来所以一直让4走到4;
初始的矩阵为 a[0][0]为1,其他都为0,因为从一开始出发。
1 0 0 0 乘以矩阵的第i列得到的数是:走到i点的情况有多少种,
这个代码是那场比赛一血的代码(模板哦)写的很清楚。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int n,m,limit;
int mod = 1e9+7;
struct matrix
{
long long a[105][105];
matrix(){memset(a,0,sizeof a);}
}a,b,c;
matrix operator *(matrix p,matrix q)//自己定义的矩阵乘法(*);
{
memset(&c,0,sizeof c);
for (int i = 0;i <= n;i++)
for (int j = 0;j <= n;j++)
for (int k = 0;k <= n;k++)
{
c.a[i][j] = (c.a[i][j] + p.a[i][k] * q.a[k][j]) % mod;
}
return c;
}
int main()
{
cin >> n >> m;
a.a[0][1] = 1;
for (int i = 1;i <= m;i++)
{
int x,y;scanf("%d%d",&x,&y);
if (x != n)
b.a[x][y]++;
if (y != n)
b.a[y][x]++;
}
b.a[n][n] = 1;
cin >> limit;
/*while(limit--)
{
a = a * b;
}*/
while (limit)
{
if (limit & 1) a = a * b;
b = b * b;
limit >>= 1;
}
cout << a.a[0][n] << endl;
}
这道题算是矩阵快速幂的入门题吧
在分享一道题http://acm.hdu.edu.cn/showproblem.php?pid=5015
杭电的挺不错的一道矩阵快速幂的题。
我上一篇博客有这道题的题解,写的比较详细。