HDU_1874 畅通工程续(SPFA)

  查SPFA的资料时偶尔看到一种运用,然后很淡定的敲之1A了

15MS+328k   code:

#include <iostream>
#include
<cstdio>
#include
<cstring>
using namespace std;

const int N = 207;
const int inf = 100000000;

int vis[N], map[N][N];
int dis[N], q[N];

void spfa(int n, int s)
{
int i, f, r, p;
memset(vis,
0, sizeof(vis));
for(i = 0; i < N; i++)
q[i]
= 0;
for(i = 0; i < n; i++)
dis[i]
= inf;
dis[s]
= 0; vis[s] = 1;
q[
0] = s; f = 0; r = 1;
while(f < r)
{
p
= q[f];
for(i = 0; i < n; i++)
if(dis[i] > map[p][i] + dis[p])
{
dis[i]
= map[p][i] + dis[p];
if(!vis[i])
{
q[r
++] = i;
vis[i]
= 1;
}
}
vis[p]
= 0;
f
++;
}
}

int main()
{
int n, m, i, j, a, b, c;
//freopen("data.in", "r", stdin);
while(~scanf("%d%d", &n, &m))
{
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
{
map[i][j]
= inf;
if(i == j) map[i][j] = 0;
}
while(m--)
{
scanf(
"%d%d%d", &a, &b, &c);
if(c < map[a][b])
map[a][b]
= map[b][a] = c;
}
scanf(
"%d%d", &a, &b);
spfa(n, a);
if(dis[b] < inf)
printf(
"%d\n", dis[b]);
else
printf(
"-1\n");
}
return 0;
}

你可能感兴趣的:(SPFA)