A strange lift HDU - 1548(BFS)

#include <stdio.h>
#include <cstring>
#include <queue>

using namespace std; 

struct Node
{
    int x;
    int count;
};

struct List
{
    int p[2];     //正负 
}list[402];   //存贮电梯的ki 

bool mark[202]; 

queue<Node> q;

int BFS(int a, int b, int n)
{
    Node tmp;
    tmp.x = a;
    tmp.count = 0;
    mark[a] = true;
    q.push(tmp);
    int t;
    while(!q.empty())
    {
        Node cur = q.front();
        q.pop();
        if(cur.x == b)
            return cur.count;
        
        for(int i = 0; i < 2; i++)
        {
            t = cur.x + list[cur.x].p[i];
            if(t > b || t < 1)
                continue;
            if(mark[t])
                continue;
            mark[t] = true;
            Node next;
            next.x = t;
            next.count = cur.count + 1;
            q.push(next);     
        }
    } 
    return -1;
}

int main()
{
    int n, a, b;
    while(~scanf("%d", &n) && n != 0)
    {
        scanf("%d%d", &a, &b);
        for(int i = 1; i <= n; i++)
        {
            scanf("%d", &list[i].p[0]);
            list[i].p[1] = -list[i].p[0];
        }
            
        while(!q.empty())
            q.pop();
        memset(mark, 0, sizeof(mark));
        int ans = BFS(a, b, n);
        if(ans != -1)
            printf("%d\n", ans);
        else
            printf("-1\n");
    }
    
    return 0;

猜你喜欢

转载自blog.csdn.net/mch2869253130/article/details/82222860