矩阵快速幂 武汉组队赛

题址: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 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 100N100) and the number of edges MM (M\le N(N-1)/2MN(N1)/2).

The ii-th line of next MM lines contains two numbers u_iui and v_ivi, which respents an edge (u_i, v_i)(ui,vi).

The last line contains the deadline TT(T\le 10^9T109).

Output

The number of plan to reach the destination by deadline module 10^9+7109+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

杭电的挺不错的一道矩阵快速幂的题。

我上一篇博客有这道题的题解,写的比较详细。












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值