HDU 1548 BFS入門

【題目鏈接】
http://acm.hdu.edu.cn/showproblem.php?pid=1548

【解題報告】
從A出發,問到B的最短路徑。
其實就是一個最短路問題。使用優先隊列維護一下就好。不熟悉的人可能會用深搜去求解,不過暫時沒想明白深搜會錯到哪裏,留個坑以後補。
暫時遠離ACM圈,以後隨心情做點題,一切事情隨緣吧。

【參考代碼】

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;

const  int  maxn=1e3;

int N,A,B;
int K[maxn],vis[maxn];

struct Node{
      int ranks,pos;

      bool operator < ( const Node& rhs )const{
            return ranks>rhs.ranks;
      }
};

priority_queue<Node>q;
void update( int p, int  rhs )
{
      if(!vis[p])
      {
            Node now; now.pos=p; now.ranks=rhs+1;
            q.push( now );
            vis[p]=1;
      }
}

int solve()
{
      while( !q.empty() )q.pop();
      vis[A]=1;
      Node start; start.pos=A; start.ranks=0;
      q.push(start);
      while(!q.empty())
      {
            Node now=q.top(); q.pop();
            if( now.pos==B ) return  now.ranks;
            int down=now.pos-K[ now.pos ];
            int up=now.pos+K[now.pos];
            if(  down>0 ) update( down,now.ranks );
            if( up<=N ) update( up,now.ranks );
      }
      return -1;
}

int main()
{
      while( ~scanf( "%d",&N ) && N  )
      {
            scanf( "%d%d",&A,&B );
            memset( vis,0,sizeof vis );
            for( int i=1;i<=N;i++ ) scanf( "%d",K+i );
            printf( "%d\n",solve() );
      }

      return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章