讲解:8.14 最小环——信息学奥赛培训课程_哔哩哔哩_bilibili
模板题1:U84618 【模板】Floyd最小环 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
模板题2:Problem - 1599 (hdu.edu.cn)
这个算法的原理还没有理解透彻,代码也不知道哪里出错了...先放在这,等以后仔细研究。
#include<bits/stdc++.h>
using namespace std;
int n, m;
int D[105][105];
int w[105][105];
int main(void)
{
while (scanf_s("%d%d", &n, &m) == 2)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
if (i != j)
D[i][j] = w[i][j] = 1e9;
}
for (int i = 1; i <= m; i++)
{
int a, b, c;
scanf_s("%d%d%d", &a, &b, &c);
w[a][b] = w[b][a] = c;
D[a][b] = D[b][a] = c;
}
int ans = 1e9;
for (int k = 1; k <= n; k++)
{
for (int i = 1; i <= k - 1; i++)
{
for (int j = i + 1; j <= k - 1; j++)
{
if (D[i][j] + w[j][k] + w[k][i] < ans)
ans = D[i][j] + w[j][k] + w[k][i];
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (D[i][j] > D[i][k] + D[k][j])
D[i][j] = D[i][k] + D[k][j];
}
}
}
if (ans == 1e9)
cout << "It's impossible.\n";
else
cout << ans<<endl;
memset(D, 0, sizeof(D));
memset(w, 0, sizeof(w));
}
return 0;
}