2018 杭电多校3

题目链接

Problem Description
There are $$$n$$$ intersections in Bytetown, connected with $$$m$$$ one way streets. Little $$$Q$$$ likes sport walking very much, he plans to walk for q days. On the $$$i$$$-th day, Little $$$Q$$$ plans to start walking at the $$$s_i$$$-th intersection, walk through at least k$$$_i$$$ streets and finally return to the $$$t_i$$$-th intersection.
Little $$$Q$$$'s smart phone will record his walking route. Compared to stay healthy, Little $$$Q$$$ cares the statistics more. So he wants to minimize the total walking length of each day. Please write a program to help him find the best route.
Input
The first line of the input contains an integer $$$T(1≤T≤10)$$$, denoting the number of test cases.
In each test case, there are 2 integers $$$n,m(2≤n≤50,1≤m≤10000)$$$ in the first line, denoting the number of intersections and one way streets.
In the next m lines, each line contains 3 integers $$$u_i,v_i,w_i(1≤u_i,v_i≤n,u_i≠v_i,1≤w_i≤10000)$$$, denoting a one way street from the intersection $$$u_i$$$ to $$$v_i$$$, and the length of it is $$$w_i$$$.
Then in the next line, there is an integer $$$q(1≤q≤100000)$$$, denoting the number of days.
In the next $$$q$$$ lines, each line contains 3 integers $$$s_i,t_i,k_i(1≤s_i,t_i≤n,1≤k_i≤10000)$$$, describing the walking plan.
Output
For each walking plan, print $$$a$$$ single line containing an integer, denoting the minimum total walking length. If there is no solution, please print -1.
Sample Input
2
3 3
1 2 1
2 3 10
3 1 100
3
1 1 1
1 2 1
1 3 1
2 1
1 2 1
1
2 1 1
Sample Output
111
1
11
-1
题意
有一个n个点,m条有向边的图,每次询问求从s到t至少经过k条边的最短路径长度
分析
节点最多只有50个,为了高效的处理如此多的询问,肯定需要预处理。首先需要知道的是,有一个数据结构,特别适合存储在图上“转移几次的最短距离”,那就是邻接矩阵。如果邻接矩阵$$$A$$$用$$$A_{ij}=0/1$$$来记录$$$i, j$$$之间是否有一条有向边,那么$$$A imes A$$$的结果也是一个矩阵,$$$A^2_{ij}$$$的含义是从$$$i$$$出发走两步到$$$j$$$的方案个数。邻接矩阵的乘法之所以这么神奇,原理在于矩阵乘法的过程:$$$$$${A^2}_{ij}=sum_{k=1}^n A_{ik} imes A_{kj}$$$$$$ $$$A_{ik}$$$ 可以理解为从$$$i$$$走到$$$k$$$的方案个数
$$$A_{kj}$$$ 可以理解为从$$$k$$$走到$$$j$$$的方案个数
那么最后求和的过程就是把$$$i$$$到$$$j$$$的所有方案求和了。以此类推,就能算出所有的方案个数。
回到这道题中,如果把矩阵乘法的细节修改一下,让$$$A_{ik}$$$ 记录$$$i$$$到$$$k$$$的最短距离,$$$A_{kj}$$$记录$$$k$$$到$$$j$$$的最短距离,计算$$${A^2}_{ij}$$$的过程变为取最小值,也就是$$$$$${A^2}_{ij}=min_{k}(A_{ik}+A_{kj})$$$$$$,就可以用类似矩阵乘法的思想,很快得到转移k步任意两点之间最短距离的表。
总结
text
原文地址:https://www.cnblogs.com/tobyw/p/9415056.html