1013&&1014 A strange lift

来源:互联网 发布:360验机软件 编辑:程序博客网 时间:2024/06/05 05:42

题意:
有一个特别的电梯,第i层有一个对应的数字ki, 对于第i层按上升键up可升上到i+k[i]层,按下降键down到达i-k[i]层,到达的楼层最高不能超过n层,最低不能小于1层。给你一个起点A和终点B,问最少要按几次上升键或者下降键到达目的地。
思路:
把每一层都看成一个节点,问题就可以变成求起点到终点的最短路径问题。与上课讲的那个左右移动到终点的一样 只不过变成了上下移动

// ConsoleApplication18.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include<fstream>#include<iostream>#include<cstdio>   #include<queue>   #include<cstring>   using namespace std;#define maxn 250   bool visit[maxn];int maze[maxn][2];   int n, start, end;struct node{    int pos, t;}temp, p;queue<node> q;int BFS(){    memset(visit, false, sizeof(visit));    while (!q.empty())    {        temp = q.front();        q.pop();        visit[temp.pos] = true;        if (temp.pos == end)            return temp.t;        int up = maze[temp.pos][0], down = maze[temp.pos][1];        if (up != -1 && !visit[up])        {            p.pos = up;            p.t = temp.t + 1;            q.push(p);        }        if (down != -1 && !visit[down])        {            p.pos = down;            p.t = temp.t + 1;            q.push(p);        }    }    return -1;}int main(){    fstream cin("E:/C++/IN/aaa.txt");    while (cin>>n&&n)    {        cin>>start>>end;        memset(maze, -1, sizeof(maze));        while (!q.empty())            q.pop();        for (int i = 1;i <= n;i++)        {            int t;            cin>>t;            temp.pos = i;            maze[i][0] = maze[i][1] = -1;            if (i + t <= n)                maze[i][0] = i + t;            if (i - t >= 1)                maze[i][1] = i - t;            if (i == start)            {                temp.t = 0;                q.push(temp);            }        }        temp = q.front();        cout<<BFS()<<endl;    }    return 0;}
0 0
原创粉丝点击