hdu1548 A strange lift(bfs 或Dijkstra最短路径)


#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define M 205
#define INF 0x3f3f3f3f
using namespace std;

int map[M][M];
int d[M], vis[M];
int n;
int b, e;

void Dijkstra(){
   memset(d, 0x3f, sizeof(d));
   memset(vis, 0, sizeof(vis));
   d[b]=0;
   vis[b]=1;
   int root=b;
   for(int j=1; j<n; ++j){
       int minLen=INF, p;    
       for(int i=1; i<=n; ++i){
          if(!vis[i] && d[i] > d[root] + map[root][i])
              d[i] = d[root] + map[root][i];        
          if(!vis[i] && minLen>d[i]){
             p=i;
             minLen=d[i];           
          }
       }
       if(minLen==INF)
          return;
       root=p;
       vis[root]=1;
   }     
}

int main(){
   while(cin>>n && n){
       cin>>b>>e;
       memset(map, 0x3f, sizeof(map));
       for(int i=1; i<=n; ++i){
          int x, xx;
          cin>>x;
          map[i][i]=0;// i+(-)x 表示 从第i层可以到达第 i+(-)x层 
          xx=i-x;
          if(xx>=1) map[i][xx]=1;
          xx=i+x;
          if(xx<=n)  map[i][xx]=1;      
       }             
       Dijkstra();
       if(d[e]==INF)
          cout<<"-1"<<endl;
       else
          cout<<d[e]<<endl;
   }
   return 0;
}



/*
思路:当前电梯位置的两个方向进行搜索! 
      注意:搜索时的界限, 用x表示将要到达的电梯的位置 
            1. 首先是x>=1 
            2. x<=n
            3. vis[x]!=0 表明bfs时候没有经过这个楼层 
*/
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue> 
using namespace std;
struct node{
   int x;
   int step;       
   node(){}
   node(int x, int step){
      this->x=x;
      this->step=step;         
   }
};
queue<node>q;
int n, b, e;
int f[205];
int vis[205];

bool bfs(){
    while(!q.empty())  q.pop();
    memset(vis, 0, sizeof(vis)); 
    q.push(node(b,0));
    vis[b]=1;
    while(!q.empty()){
        node cur=q.front();
        q.pop();
        if(cur.x==e){
            cout<<cur.step<<endl;
            return true;             
        }               
        int xx;
        xx=cur.x+f[cur.x];
        if(xx==e){
           cout<<cur.step+1<<endl;
           return true;
        }
        if(xx<=n && !vis[xx]){
           q.push(node(xx, cur.step+1));
           vis[xx]=1;
        }
        xx=cur.x-f[cur.x];
        if(xx==e){
           cout<<cur.step+1<<endl;
           return true;
        }
        if(xx>=1 && !vis[xx]){
           q.push(node(xx, cur.step+1));
           vis[xx]=1;
        }
    }
    return false;
}
      
int main(){
    while(cin>>n && n){
       cin>>b>>e;
       for(int i=1; i<=n; ++i)
          cin>>f[i];
       if(!bfs())
          cout<<"-1"<<endl;            
    }
    return 0;    
}


上一篇:渗透测试指南之域用户组的范围


下一篇:js 退后一步并刷新,window.history.back(-1);这个只能后退一步不能刷新,