题目描述
Farmer John is on a boat seeking fabled treasure on one of the N (1 <= N <= 100) islands conveniently labeled 1..N in the Cowribbean Sea.
The treasure map tells him that he must travel through a certain sequence A1, A2, ..., AM of M (2 <= M <= 10,000) islands, starting on island 1 and ending on island N before the treasure will appear to him. He can visit these and other islands out of order and even more than once, but his trip must include the Ai sequence in the order specified by the map.
FJ wants to avoid pirates and knows the pirate-danger rating (0 <= danger <= 100,000) between each pair of islands. The total danger rating of his mission is the sum of the danger ratings of all the paths he traverses.
Help Farmer John find the least dangerous route to the treasure that satisfies the treasure map's requirement.输入描述:
* Line 1: Two space-separated integers: N and M * Lines 2..M+1: Line i+1 describes the ith island FJ must visit with a single integer: Ai * Lines M+2..N+M+1: Line i+M+1 contains N space-separated integers that are the respective danger rating of the path between island i and islands 1, 2, ..., and N, respectively. The ith integer is always zero.输出描述:
* Line 1: The minimum danger that Farmer John can encounter while obtaining the treasure.示例1
输入
复制
3 4 1 2 1 3 0 5 1 5 0 2 1 2 0输出
复制
7说明
There are 3 islands and the treasure map requires Farmer John to visit a sequence of 4 islands in order: island 1, island 2, island 1 again, and finally island 3. The danger ratings of the paths are given: the paths (1, 2); (2, 3); (3, 1) and the reverse paths have danger ratings of 5, 2, and 1, respectively. He can get the treasure with a total danger of 7 by traveling in the sequence of islands 1, 3, 2, 3, 1, and 3. The cow map's requirement (1, 2, 1, and 3) is satisfied by this route. We avoid the path between islands 1 and 2 because it has a large danger rating.
思路:要求按照路线顺序的最小路径长度,我们可以利用弗洛伊德算法预处理出所有点之间的最短路,然后按照路线顺序将所有最短路相加即是答案;
AC代码:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N=110,M=10010;
int d[N][N];
int n,m;
int seq[M];
void floyd()
{
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
scanf("%d",&seq[i]);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%d",&d[i][j]);
floyd();
int res=0;
for(int i=2;i<=m;i++)
res+=d[seq[i-1]][seq[i]];
cout<<res<<endl;
}