Original question: fzu 2173 http://acm.fzu.edu.cn/problem.php? PID = 1, 2173
At first, I had no clue about this question. I didn't expect it to be a matrix Rapid power. In fact, when I saw K as big, I should think of a quick power or something. Besides, n <= 50, A matrix can be used to represent a graph.
1. Why can I use a matrix power quickly?
Principle:
In the original matrix m [] [], M [u] [v] represents the cost of u to v. After obtaining the k power of the matrix, in this case, M [u] [v] represents the minimum cost of walking from u to B
Note that the multiplication of the matrix should be written as follows:
M [a] [B] = min (M [a] [1] + M [1] [B],... M [a] [N] + M [N] [B]), that is, take the minimum value instead of the sum.
2. Why?
The power of M is undoubtedly correct.
2 power of m
At this time (M [a] [B]) ^ 2 = min (M [a] [1] + M [1] [B],... M [a] [N] + M [N] [B]) is the minimum cost of enumerating a from 1 to n points to B, it is the minimum cost for a to arrive at B in two steps.
Induction:
If (M [a] [B]) ^ I represents the minimum cost for a to arrive at B in step I, then M ^ (I + 1) = min (M [a] [1]) ^ I + M [1] [B],... (M [a] [N]) ^ I + M [N] [B])
So you can do this.
(Learn from the nothing blog)
Code:
# Include <iostream> # include <cstdio> # include <cstring> # include <cmath> # include <cstdlib> # include <algorithm> # define mod 1000000007 # define lll _ int64using namespace STD; # define n 6007 struct matrix {lll M [55] [55] ;}; int N, H, K; matrix MUL (matrix A, matrix B) {matrix C; memset (C. m,-1, sizeof (C. m); For (INT I = 0; I <n; I ++) for (Int J = 0; j <n; j ++) {for (int K = 0; k <n; k ++) {if (. M [I] [k]! =-1 & B. M [k] [J]! =-1) {If (C. M [I] [J] =-1) C. M [I] [J] =. M [I] [k] + B. M [k] [J]; else C. M [I] [J] = min (C. M [I] [J],. M [I] [k] + B. M [k] [J]) ;}}return C;} matrix fastm (matrix A, int N) {If (n = 1) return; matrix res = fastm (A, n/2); Res = MUL (Res, Res); If (N & 1) RES = MUL (Res, a); Return res ;} matrix mpow (matrix A, int N) // method 2 {matrix res = A; n --; while (n) {If (N & 1) RES = MUL (Res, a); n> = 1; A = MUL (a, a);} return res;} int main () {int T, I, J, K; int U, v; lll W; matrix A, ans; scanf ("% d", & T); While (t --) {scanf ("% d ", & N, & H, & K); memset (. m,-1, sizeof (. m); for (I = 0; I View code