HDU-1548 A Strange Lift
题意:一共N层电梯,到达第x层电梯可以向上或向下移动a[x]的层数,问最短需要几次操作到达指定层数。
主要是要处理好操作数量的动态变化关系,如果在bfs或者dfs里面随便写个num++肯定会出问题
dfs,bfs,最短路dijkstra 貌似都能做
1.bfs
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include <memory.h>
#include<deque>
#include<queue>
#define ll long long
#define pb push_back
using namespace std;
struct node
{
int x,step;
} m,n1,n2;
bool map[300],flag;
int n,a,b,w[300];
int main()
{
while(scanf("%d",&n),n)
{
queue<node> Q;
if (n==0)
break;
cin>>a>>b;
for (int i=1; i<=n; i++)
{cin>>w[i];map[i]=false;}
n1.x=a;
n1.step=0;
flag=false;
map[n1.x]=true;
Q.push(n1);
while(!Q.empty())
{
m=Q.front();
Q.pop();
if (m.x==b)
{
flag=true;
break;
}
n1.x=m.x-w[m.x];
n2.x=m.x+w[m.x];
if (n1.x>0&&n1.x<=b&&!map[n1.x])
{
n1.step=m.step+1;
map[n1.x]=true;
Q.push(n1);
}
if (n2.x>0&&n2.x<=b&&!map[n2.x])
{
n2.step=m.step+1;
map[n2.x]=true;
Q.push(n2);
}
}
if (flag)
cout<<m.step<<endl;
else
cout<<-1<<endl;
}
return 0;
}
2.dfs
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<queue>
#include<map>
#define ll long long
#define pb push_back
using namespace std;
const int maxn=209;
const int INF=1e9;
int n,sx,ex,step;
int w[maxn];
int ans;
int book[maxn];//到达这个楼层所需要的最小操作数
void dfs(int sx,int step)
{
if (sx<1||sx>n)
return;
if (sx==ex&&step<ans)//这个比较貌似很关键,一开始没写这个直接输出stepWA了
{
ans=step;
return;
}
if (step>=book[sx])
return;
book[sx]=step;
dfs(sx+w[sx],step+1);
dfs(sx-w[sx],step+1);
return;
}
int main()
{
while(~scanf("%d",&n)&&n)
{
scanf("%d%d",&sx,&ex);
for (int i=1; i<=n; i++)
{
scanf("%d",&w[i]);
book[i]=INF;
}
ans=INF;
step=0;
dfs(sx,step);
if (ans==INF)
cout<<-1<<endl;
else
cout<<ans<<endl;
}
return 0;
}