hdu 3631 Shortest Path

时间:2023-11-26 13:59:08

floyd算法好像很奇妙的样子。可以做到每次加入一个点再以这个点为中间点去更新最短路,效率是n*n。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std; const int maxn = ;
const int INF = 0x7FFFFFFF;
int A[maxn][maxn], flag[maxn];
int n, m, q; void floyd(int x)
{
int i, j;
for (i = ; i < n; i++)
{
for (j = ; j < n; j++)
{
if (i == x || j == x) continue;
if (A[i][x] == INF || A[x][j] == INF) continue;
if (A[i][x] + A[x][j] < A[i][j]) A[i][j] = A[i][x] + A[x][j];
}
}
} int main()
{
int i, j, u, v, c, koko = ;
while (~scanf("%d%d%d", &n, &m, &q))
{
if (n == && m == && q == ) break;
memset(flag, , sizeof(flag));
for (i = ; i <= n; i++)
{
for (j = ; j <= n; j++)
{
if (i == j) A[i][j] = ;
else A[i][j] = INF;
}
}
for (i = ; i < m; i++)
{
scanf("%d%d%d", &u, &v, &c);
if (c < A[u][v]) A[u][v] = c;
}
int oo, pp, qq;
if (koko != ) printf("\n");
printf("Case %d:\n", koko++);
for (i = ; i < q; i++)
{
scanf("%d", &oo);
if (oo == )
{
scanf("%d", &pp);
if (flag[pp] == ) printf("ERROR! At point %d\n", pp);
else if (flag[pp] == ){ flag[pp] = ; floyd(pp); }
}
else if (oo == )
{
scanf("%d%d", &pp, &qq);
if (flag[pp] == || flag[qq] == )printf("ERROR! At path %d to %d\n", pp, qq);
else
{
if (A[pp][qq] == INF) printf("No such path\n");
else printf("%d\n", A[pp][qq]);
}
}
}
}
return ;
}