摘要:
Floyd算法求解最长路
问题描述:
原题链接[洛谷P2196挖地雷](https://www.luogu.com.cn/problem/P2196)代码以及详细注释:
#include <iostream>
#include <stdio.h>
#include <vector>
#pragma warning(disable:4996)
using namespace std;
class solution {
public:
int n;
vector<vector<int>> cost;
vector<vector<int>> key;
vector<int> w;
void floyd() {
cin >> n;
w.resize(n + 1);
cost.resize(n + 1, vector<int>(n + 1,0));
key.resize(n + 1, vector<int>(n + 1,0));
for (int i = 1; i <= n; ++i)
{
cin >> w[i];
}
for(int i=1;i<n;++i)
for (int j = i + 1; j <= n; ++j)
{
int temp;
cin >> temp;
cost[i][j] = temp * w[j];
}
for(int k=1;k<=n;++k)
for(int i=1;i<=n;++i)
for (int j = 1; j <= n; ++j)
{
if (i!=k&&k!=j&&cost[i][k]!=0 && cost[k][j]!=0 && cost[i][j] < cost[i][k] + cost[k][j])
{
cost[i][j] = cost[i][k] + cost[k][j];
key[i][j] = k;
}
}
int ans = 0;
pair<int, int> res;
for(int i=1;i<=n;++i)
for (int j = i; j <= n; ++j)
{
if (ans < cost[i][j]+w[i])
{
ans = cost[i][j]+w[i];
res = {
i,j };
}
}
outpath(res.first, res.second);
cout << endl<< ans;
}
void outpath(int i, int j)
{
cout << i;
out(i, j);
}
void out(int i, int j)
{
if (i == j)
return;
if (key[i][j] == 0)
cout <<" "<<j;
else
{
out(i, key[i][j]);
out(key[i][j], j);
}
}
};
int main() {
//freopen("in.txt", "r", stdin);
solution s;
s.floyd();
return 0;
}