307-09-10矩阵乘法与快速幂
矩阵乘法
定义矩阵
矩阵乘法的结合律
矩阵乘法存在结合律,首先定义矩阵
对于
由此,可以证明,矩阵的乘法具有结合律。
Floyd 算法
Floyd算法的主要目的是在一张图上求任意两点之间的最短路,而最短路的核心思想其实可以由一个方程来表达:
其表示
但是它的初始化值得注意,其应该初始化为一个图论的单位矩阵,即主对角线的值为
为了实现上述思想,以下为代码实现:
注:Floyd算法的k的那层循环必须在最外面,否则有些值无法被更新。
快速幂
如果我们要计算
换言之,如果我们要计算
矩阵乘法结合律的应用
前文已经证明了矩阵的乘法具有结合律,而既然有结合律那么自然可以使用快速幂求一个矩阵的幂运算,对于基于乘法的快速幂算法而言,需要修改的是运算符和初始化值。
在矩阵乘法中的初始化值也比较重要,当然这一步也可以忽略,因为执行
这样做的原因是对于任意一个矩阵
代码(模板P3390):
使用矩阵乘法(快速幂)求斐波那契数列
斐波那契数列:
如果使用递归,
现在购下一个矩阵
由于
则:
所以可以得到结论:
所以我们可以得到结论:有斐波那契数列前后连续的两项组成的一个列向量的矩阵乘上一个矩阵
可以得到由斐波那契数列的后一项和当前项组成的另外一个列向量。
可以得到以下的推论:
由于前文证明的矩阵乘法的结合律,可以得到结论:
由此可以通过矩阵乘法的快速幂解决斐波那契数列的第
P2886 [USACO07NOV]牛继电器Cow Relays
For their physical fitness program, N (2 ≤ N ≤ 1,000,000) cows have decided to run a relay race using the T (2 ≤ T ≤ 100) cow trails throughout the pasture.
Each trail connects two different intersections (1 ≤ I1i ≤ 1,000; 1 ≤ I2i ≤ 1,000), each of which is the termination for at least two trails. The cows know the lengthi of each trail (1 ≤ lengthi ≤ 1,000), the two intersections the trail connects, and they know that no two intersections are directly connected by two different trails. The trails form a structure known mathematically as a graph.
To run the relay, the N cows position themselves at various intersections (some intersections might have more than one cow). They must position themselves properly so that they can hand off the baton cow-by-cow and end up at the proper finishing place.
Write a program to help position the cows. Find the shortest path that connects the starting intersection (S) and the ending intersection (E) and traverses exactly N cow trails.
给出一张无向连通图,求S到E经过k条边的最短路。
题解:
对一个图的邻接矩阵进行平方,得到的每个元素
在这道题中要求经过
设恰好通过
我们可以对比一下类似地方程:设通过
我们可以简化一下方程:
对于一组点
值得注意的是这其实与Floyd算法实现有所不同,因为
通过上面的这个式子,不难想到:如果要进过
首先,证明结合律的正确性:
定义新运算:矩阵
综上所述,这是一道通过快速幂来进行矩阵的快速变换的最短路问题。
过程:设单位矩阵为
对于每组点
代码: