作者在 2010-08-01 22:17:57 发布以下内容
题目链接:hdu1548
声明:本文摘自 sunkehappy
#include <stdio.h>
#define DEBUG 0
const int N=300 ;
const int Max = 10000000 ;
int n, map[N][N], used[N], dis[N] ;
void Dijkstra( int a, int b )
{
int i, j, index, min ;
for( i=1; i<=n; ++i ){
dis[i] = map[a][i] ;
used[i] = 0 ;
}
used[a] = 1 ;
for( i=1; i<=n; ++i ){
index = a ;
min = Max ;
for( j=1; j<=n; ++j ){
if( !used[j] && min > dis[j] ){
min = dis[j] ;
index = j ;
}
}
used[index] = 1 ;
for( j=1; j<=n; ++j ){
if( dis[j] > dis[index]+map[index][j] )
dis[j] = dis[index]+map[index][j] ;
}
}
if( dis[b] == Max ){
//printf("%d\n", dis[b] ) ;
printf("-1\n") ;
}
else
printf("%d\n", dis[b] ) ;
}
int main( )
{
#if DEBUG
freopen("C:\\Documents and Settings\\Administrator\\桌面\\in.in","r",stdin) ;
freopen("C:\\Documents and Settings\\Administrator\\桌面\\out.out","w",stdout) ;
#endif
int i, j, a, b, temp ;
while( scanf("%d", &n) && n ){
for( i=1; i<=n; ++i ){
for( j=1; j<=n; ++j )
map[i][j] = Max ;
map[i][i] = 0 ;
}
scanf("%d%d", &a, &b ) ;
for( i=1; i<=n; ++i ){
scanf("%d", &temp ) ;
if( i - temp > 0 )
map[i][i-temp] = 1 ;
if( i + temp <= n )
map[i][i+temp] = 1 ;
}
Dijkstra( a, b ) ;
}
return 0 ;
}
#include <stdio.h>
#define DEBUG 0
const int N=300 ;
const int Max = 10000000 ;
int n, map[N][N], used[N], dis[N] ;
void Dijkstra( int a, int b )
{
int i, j, index, min ;
for( i=1; i<=n; ++i ){
dis[i] = map[a][i] ;
used[i] = 0 ;
}
used[a] = 1 ;
for( i=1; i<=n; ++i ){
index = a ;
min = Max ;
for( j=1; j<=n; ++j ){
if( !used[j] && min > dis[j] ){
min = dis[j] ;
index = j ;
}
}
used[index] = 1 ;
for( j=1; j<=n; ++j ){
if( dis[j] > dis[index]+map[index][j] )
dis[j] = dis[index]+map[index][j] ;
}
}
if( dis[b] == Max ){
//printf("%d\n", dis[b] ) ;
printf("-1\n") ;
}
else
printf("%d\n", dis[b] ) ;
}
int main( )
{
#if DEBUG
freopen("C:\\Documents and Settings\\Administrator\\桌面\\in.in","r",stdin) ;
freopen("C:\\Documents and Settings\\Administrator\\桌面\\out.out","w",stdout) ;
#endif
int i, j, a, b, temp ;
while( scanf("%d", &n) && n ){
for( i=1; i<=n; ++i ){
for( j=1; j<=n; ++j )
map[i][j] = Max ;
map[i][i] = 0 ;
}
scanf("%d%d", &a, &b ) ;
for( i=1; i<=n; ++i ){
scanf("%d", &temp ) ;
if( i - temp > 0 )
map[i][i-temp] = 1 ;
if( i + temp <= n )
map[i][i+temp] = 1 ;
}
Dijkstra( a, b ) ;
}
return 0 ;
}