标签:最短路
5 1 5 3 3 1 2 5 0
3
Statistic | Submit | Discuss | Note
BFS或者最短路
#include <map>
#include <set>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 210;
int F[N];
bool vis[N];
int n, a, b;
struct node
{
int cur_fl;
int step;
};
void bfs()
{
queue<node>qu;
memset (vis, 0, sizeof(vis));
while (!qu.empty())
{
qu.pop();
}
node tmp1, tmp2;
tmp1.step = 0;
tmp1.cur_fl = a;
bool flag = false;
int ans;
qu.push(tmp1);
vis[tmp1.cur_fl] = 1;
while(!qu.empty())
{
tmp1 = qu.front();
qu.pop();
if (tmp1.cur_fl == b)
{
flag = true;
ans = tmp1.step;
break;
}
if (tmp1.cur_fl + F[tmp1.cur_fl] <= n && !vis[tmp1.cur_fl + F[tmp1.cur_fl]])
{
vis[tmp1.cur_fl + F[tmp1.cur_fl]] = 1;
tmp2.cur_fl = tmp1.cur_fl + F[tmp1.cur_fl];
tmp2.step = tmp1.step + 1;
// printf("cur-floor is %d\n", tmp2.cur_fl);
qu.push(tmp2);
}
if (tmp1.cur_fl - F[tmp1.cur_fl] >= 1 && !vis[tmp1.cur_fl - F[tmp1.cur_fl]])
{
vis[tmp1.cur_fl - F[tmp1.cur_fl]] = 1;
tmp2.cur_fl = tmp1.cur_fl - F[tmp1.cur_fl];
tmp2.step = tmp1.step + 1;
// printf("cur-floor is %d\n", tmp2.cur_fl);
qu.push(tmp2);
}
}
if (flag)
{
printf("%d\n", ans);
return;
}
printf("-1\n");
}
int main()
{
while(~scanf("%d", &n), n)
{
scanf("%d%d", &a, &b);
for (int i = 1; i <= n; ++i)
{
scanf("%d", &F[i]);
}
bfs();
}
return 0;
}标签:最短路
原文地址:http://blog.csdn.net/guard_mine/article/details/41286605