【HDU 1599】最小环_#define

在一个无向图里找到最小环,环里面的元素大于等于3.其实时floyd的引用。考虑floyd算法,首先枚举中间点k.在利用k来松弛s[i][j]。(s[i][j]代表i到j的最短路)。在算法没有执行的时候,从i到j肯定是不经过k点的,所以如果s[i][j]!=INF,并且i-k,k-j存在路径,那么说明原图中存在环路。并且可以这个环路的点的数量大于等于3.所以把这个值记录一下,取个最小就是答案。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 110;
ll s[N][N], ss[N][N];
#define INF 2e9
int n, m;
void floyd()
{
ll ans = INF;
for (int k = 1; k <= n; k++)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if(j!=i&&k!=i&&j!=k)
ans = min(ans, s[i][j] + ss[i][k] + ss[k][j]);

}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
s[i][j] = min(s[i][j], s[i][k] + s[k][j]);
}
}
}
if (ans == INF)
{
puts("It's impossible.");
}
else
{
cout << ans << endl;
}
}
int main()
{
while (~scanf("%d%d", &n, &m))
{
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)s[i][j] = ss[i][j] = INF;
for (int i = 1; i <= m; i++)
{
ll u, v, w;
scanf("%lld%lld%lld", &u, &v, &w);
s[u][v] = min(s[u][v], w);
s[v][u] = s[u][v];
ss[u][v] = ss[v][u] = s[u][v];
}
floyd();
}
}