HDU 1548 A strange lift

题目地址:点击打开链接

思路:单向图,有不可能的情况,用BFS做也可以

AC代码:

#include<iostream>
#include<cstring>
#define MAX1 400000

using namespace std;

int map[210][210],visit[210],dist[210];
int n,a,b;
void dijkstra()
{
    int i,j,min,k;
    for(i=1; i<=n; i++)
    {
        dist[i] = map[a][i];
        visit[i] = 0;
    }
    dist[a] = 0;
    visit[a] = 1;
    for(i=1; i<n; i++)
    {
        min = MAX1;
        for(j=1; j<=n; j++)
        {
            if(visit[j] == 0 && dist[j] < min)
            {
                min = dist[j];
                k = j;
            }
        }
        if(min == MAX1)
            return;
        visit[k] = 1;
        for(j=1; j<=n ;j++)
        {
            if(visit[j] == 0 && dist[k] + map[k][j] < dist[j])
                dist[j] = dist[k] + map[k][j];
        }
    }
}
int main()
{
    int i,j,x;
    while(cin>>n && n)
    {
        cin>>a>>b;
        for(i=1; i<=n; i++)
        {
            for(j=1; j<=n; j++)
            {
                map[i][j] = MAX1;
            }
        }
        for(i=1; i<=n; i++)
        {
            cin>>x;
            if(i+x<=n)
                map[i][i+x] = 1;
            if(i-x>=1)
                map[i][i-x] = 1;
        }
        dijkstra();//注意语句cout<<(dist[b] == MAX1 ? -1 : dist[b])
        if(dist[b]  == MAX1)
            cout<<"-1"<<endl;
        else
            cout<<dist[b]<<endl;
    }
    return 0;
}


你可能感兴趣的:(HDU 1548 A strange lift)