HD1599 find the mincost route(floyd + 最小环)

题目链接

题意:求最小环

第一反应时floyd判断,但是涉及到最少3个点,然后就不会了,又想的是 双联通分量,这个不知道为什么不对。

Floyd 判断 最小环

 #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
const int Max = + ;
int g[Max][Max], dist[Max][Max];
//dist【i】【j】保存i到j的最短路经,然后i -> j -> k 就可以枚举k, dist[i][j] + g[i][k] + g[j][k]就是一个环的权值
int mincost;
void Floyed(int n)
{
mincost = INF;
for (int k = ; k <= n; k++)
{
for (int i = ; i < k; i++)
{
for (int j = i + ; j < k; j++)
{
if (dist[i][j] != INF && g[i][k] != INF && g[k][j] != INF)
{
int temp = dist[i][j] + g[i][k] + g[k][j]; // 原先这里直接相加,一直没找到错误,爆精度
if (temp < mincost)
mincost = temp;
}
}
}
for (int i = ; i <= n; i++)
{
for (int j = ; j <= n; j++)
{
if (dist[i][k] != INF && dist[k][j] != INF)
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
}
int main()
{
int n, m;
while (scanf("%d%d", &n, &m) != EOF)
{
for (int i = ; i < Max; i++)
for (int j = ; j < Max; j++)
{
g[i][j] = INF;
dist[i][j] = INF;
}
int a, b, c;
for (int i = ; i <= m; i++)
{
scanf("%d%d%d", &a, &b, &c);
if (g[a][b] > c)
g[a][b] = g[b][a] = dist[a][b] = dist[b][a] = c;
}
Floyed(n);
if (mincost >= INF)
printf("It's impossible.\n");
else
printf("%d\n", mincost); }
return ;
}
上一篇:最小生成树 --- 求最小权值、MST


下一篇:codevs1688 求逆序对(权值线段树)