Naked Freud algorithm, specified in the title, and then elaborate on the idea;
Freudian thought:
For n nodes, if the node acts as a relay between any other two nodes i, j, the distance between i and j can be shortened, then update;
Using three cyclic updates, the complexity is O (n ^ 3);
#include<iostream> #include<vector> #include<string> using namespace std; const int maxn = 210; const int INF = 10000000; int ma [maxn] [maxn]; int n, m; int st, ed; void init() { fill(ma[0], ma[0] + maxn * maxn, INF); for (int i = 0; i < n; i++) { has [i] [i] = 0; } } void floyd() { for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (ma[i][k] != INF && ma[k][j] != INF && ma[i][k] + ma[k][j] < ma[i][j]) { in [i] [j] = in [i] [k] + in [k] [j]; } } } } } int main () { while (cin >> n >> m) { init(); int a, b, c; for (int i = 0; i < m; i++) { cin >> a >> b >> c; at [a] [b] = and [b] [a] = c; } cin >> st >> ed; floyd(); if (ma[st][ed] == INF) cout << -1 << endl; else cout << ma[st][ed] << endl; } }