把与某个楼成相连的上下楼层为边建立一个图,边的权值为1.
如:3 3 1 2 5
可建成图:
map[1][4] = 1;
map[2][5] = 1;
map[3][2] = 1;
map[3][4] = 1;
map[4][2] = 1;
然后用最短路经的解法Floyd, Bellman_Ford, SPFA, Dijkstra...
这里用的是Dijkstra解法
My Code:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int inf = 10000000;
const int N = 207;
int map[N][N];
int dis[N], vis[N];
int n;
void Dijkstra(int v)
{
int i, j;
memset(vis, 0, sizeof(vis)); //这里是个陷阱,记得要memset(vis, 0, sizeof(vis));,在这里查bug查了好一会!
for(i = 1; i <= n; i++)
{
dis[i] = map[v][i];
//printf("%d ", map[v][i]);
}
dis[v] = 0;
vis[v] = 1;
for(i = 2; i <= n; i++)
{
int flag = v, min = inf;
for(j = 1; j <= n; j++)
if(!vis[j] && dis[j] < min)
{
flag = j;
min = dis[j];
}
vis[flag] = 1;
for(j = 1; j <= n; j++)
{
if(!vis[j] && map[flag][j] < inf)
{
int newdis = dis[flag] + map[flag][j];
if(newdis < dis[j])
dis[j] = newdis;
}
}
}
}
int main()
{
//freopen("data.in", "r", stdin);
int v, u, x;
while(scanf("%d", &n), n)
{
scanf("%d%d", &v, &u);
int i, j;
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
map[i][j] = inf;
for(i = 1; i <= n; i++)
{
scanf("%d", &x);
if(i+x <= n)
map[i][i+x] = 1;
if(i-x >= 1)
map[i][i-x] = 1;
}
/*for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
printf("%10d", map[i][j]);
printf("\n");
}*/
Dijkstra(v);
/*for(i = 1; i <= n; i++)
printf("%d ", dis[i]);
printf("\n");*/
if(dis[u] < inf)
printf("%d\n", dis[u]);
else
printf("-1\n");
}
return 0;
}
VonGang原创,转载请注明:http://www.cnblogs.com/vongang/http://www.cnblogs.com/vongang/