hdu2544

dijkstra
   
     
#include " iostream "
#define Max 999999
using namespace std;
int map[ 1001 ][ 1001 ];
int visit[ 1001 ];
int n,m;
int a,b,time;
int i,j,k,_min;
int len;
void DJ()
{
for (i = 1 ;i <= len;i ++ )
{
_min
= Max;

for (j = 1 ;j <= len;j ++ )
{
if ( ! visit[j] && map[ 0 ][j] < _min)
{
_min
= map[ 0 ][j];
k
= j;
}
}
if (_min == Max) break ;

visit[k]
= 1 ;
for ( int p = 1 ;p <= len;p ++ )
{
if ( ! visit[p] && map[ 0 ][p] > map[ 0 ][k] + map[k][p])
{
map[
0 ][p] = map[ 0 ][k] + map[k][p];

}
}
}
}
int main()
{

while (cin >> n >> m,n + m)
{
for (i = 0 ;i < 1001 ;i ++ )
{
for (j = 0 ;j < 1001 ;j ++ )
map[i][j]
= Max;
}
len
= 0 ;
for (i = 0 ;i < m;i ++ )
{
scanf(
" %d%d%d " , & a, & b, & time);

if (map[a][b] > time) map[a][b] = map[b][a] = time;
if (len < a) len = a;
if (len < b) len = b;
}
memset(visit,
0 , sizeof (visit));

map[
0 ][ 1 ] = 0 ;
DJ();
cout
<< map[ 0 ][n] << endl;
}
return 0 ;
}
floyd
   
     
#include " iostream "
#define Max 999999
using namespace std;
int map[ 1001 ][ 1001 ];
int visit[ 1001 ];
int n,m;
int a,b,time;
int i,j,k,_min;
int len;
void Floyd()
{
for (k = 1 ;k <= len;k ++ )
{
for (i = 1 ;i <= len;i ++ )
{
for (j = 1 ;j <= len;j ++ )
{
if ( ! visit[j] && map[i][j] > map[i][k] + map[k][j])
map[i][j]
= map[i][k] + map[k][j];
}
}
}
}
int main()
{

while (cin >> n >> m,n + m)
{
for (i = 0 ;i < 1001 ;i ++ )
{
for (j = 0 ;j < 1001 ;j ++ )
map[i][j]
= Max;
}
len
= 0 ;
for (i = 0 ;i < m;i ++ )
{
scanf(
" %d%d%d " , & a, & b, & time);

if (map[a][b] > time) map[a][b] = map[b][a] = time;
if (len < a) len = a;
if (len < b) len = b;
}
memset(visit,
0 , sizeof (visit));
map[
0 ][ 1 ] = 0 ;
Floyd();
cout
<< map[ 1 ][n] << endl;
}
return 0 ;
}
View Code
   
     
#include < stdio.h >
#include
< string .h >
#define Max 999999999
#define M 1005
#define N 1001
int map[M][M];
int dir[M];
int n , m ;
int a , b , c ;
int len;

void DJ( int v)
{
bool visit[N] = { false };

int i , j , p;
for (i = 1 ; i <= n ; i ++ )
dir[i]
= map[v][i];
dir[v]
= 0 ;
visit[v]
= true ;
for (i = 1 ;i <= n;i ++ )
{
int Min = Max;
int k = v ;
for (j = 1 ;j <= n;j ++ )
{
if ( ! visit[j] && dir[j] < Min )
{

k
= j;
Min
= dir[j];
}
}
visit[k]
= true ;
for ( p = 1 ; p <= n; p ++ )
{
if ( ! visit[p] && map[k][p] < Max && dir[p] > dir[k] + map[k][p] )
{
dir[p]
= dir[k] + map[k][p];
}
}
}
}
int main()
{

while (scanf( " %d%d " , & n, & m) != EOF && (n + m))
{
int i,j;
for (i = 0 ; i <= 1000 ; i ++ )
for (j = 0 ; j <= i; j ++ )
{
map[i][j]
= Max;
map[j][i]
= Max;
}

for (i = 0 ;i < m;i ++ )
{
scanf(
" %d%d%d " , & a, & b, & c);
if (map[a][b] > c) map[a][b] = map[b][a] = c;

}

DJ(
1 );
printf(
" %d\n " ,dir[n]);

}
return 0 ;

}

你可能感兴趣的:(HDU)