AcWing 344. 观光之旅
原题链接
中等
作者:
zqc
,
2021-04-08 10:51:28
,
所有人可见
,
阅读 322
#include <bits/stdc++.h>
using namespace std;
const int N = 110, INF = 0x3f3f3f3f;
int dist[N][N], g[N][N];
int pos[N][N];
int path[N];
int cnt;
void get_path(int i, int j)
{
if (!pos[i][j]) return;
int k = pos[i][j];
get_path(i, k);
path[cnt ++] = k;
get_path(k, j);
}
int main(void)
{
int n, m;
cin >> n >> m;
memset(g, 0x3f, sizeof g);
for (int i = 1; i <= n; i ++) g[i][i] = 0;
for (int i = 0; i < m; i ++)
{
int a, b, c;
cin >> a >> b >> c;
g[a][b] = g[b][a] = min(g[a][b], c);
}
memcpy(dist, g, sizeof dist);
int 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 ((long long int)dist[i][j] + g[i][k] + g[k][j] < res)
{
res = dist[i][j] + g[i][k] + g[k][j];
cnt = 0;
path[cnt ++] = k;
path[cnt ++] = i;
get_path(i, j);
path[cnt ++] = j;
}
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= n; j ++)
if (dist[i][k] + dist[k][j] < dist[i][j])
{
dist[i][j] = dist[i][k] + dist[k][j];
pos[i][j] = k;
}
}
if (res == INF)
printf("No solution.\n");
else
{
for (int i = 0; i < cnt; i ++)
cout << path[i] <<" ";
cout << endl;
}
return 0;
}