AcWing 344.观光之旅(floyd)
作者:
冰冷酒
,
2022-04-11 00:19:14
,
所有人可见
,
阅读 203
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
const int N = 110, INF = 0x3f3f3f3f;
int g[N][N], d[N][N];
int path[N][N];
int pos[N], cnt = 0;
int n, m;
void get_dist(int i, int j) // 递归输出路径
{
if (path[i][j] == 0) return ;
int k = path[i][j]; // 每当有转移点,就加进去并递归
get_dist(i, k);
pos[++ cnt] = k;
get_dist(k, j);
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> m;
memset(g, 0x3f, sizeof(g));
for (int i = 1; i <= m; i ++)
{
int a, b, c;
cin >> a >> b >> c;
g[a][b] = g[b][a] = min(g[a][b], c); // 判重边
}
memcpy(d, g, sizeof(d));
LL res = INF;
for (int k = 1; k <= n; k ++)
{
for (int i = 1; i < k; i ++)
for (int j = i + 1; j < k; j ++)
{
if ((LL)d[i][j] + g[j][k] + g[k][i] < res) // 如果这个环更小就更新
{
res = d[i][j] + g[j][k] + g[k][i]; // 更新最小环的长度
cnt = 0;
pos[++ cnt] = j; // 依次把边加进去
pos[++ cnt] = k;
pos[++ cnt] = i;
get_dist(i, j);
}
}
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= n; j ++)
if (d[i][j] > d[i][k] + d[k][j]) // floyd求最短路并记录转移点
{
d[i][j] = d[i][k] + d[k][j];
path[i][j] = k;
}
}
if (cnt == 0)
{
cout << "No solution." << '\n';
return 0;
}
for (int i = 1; i <= cnt; i ++) cout << pos[i] << ' ';
cout << '\n';
return 0;
}
求关注