题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1548
题意:
坐电梯 电梯上有上和下两种操作 给你开始的楼层和目的的楼层 让你求出 最少经过多少次操作 到达目的楼层
解题思路:
一种是 bfs 一种是 最短路 (dfs也尝试了一下 但是超时了 感觉这种问题 还是尽量少用dfs吧)
AC代码:bfs
#include<iostream>
#include<queue>
using namespace std;
const int maxp=205;
int mark[maxp];
int flor[maxp];
int n;
struct point
{
int f,step;
void operator =(const point &a)
{
f=a.f;
step=a.step;
}
};
void bfs(int s,int e)
{
queue<point> que;
point temp;
temp.f=s;
temp.step=0;
que.push(temp);
while(!que.empty())
{
int newflor;
temp=que.front();
que.pop();
if(temp.f==e)
{
cout<<temp.step<<endl;
return;
}
int nowflor=temp.f;
int nowstep=temp.step;
newflor=nowflor+flor[nowflor];
if(newflor<=n&&!mark[newflor])
{
temp.f=newflor;
temp.step++;
mark[newflor]=1;
que.push(temp);
}
newflor=nowflor-flor[nowflor];
if(newflor>=1&&!mark[newflor])
{
temp.f=newflor;
temp.step=nowstep+1;
mark[newflor]=1;
que.push(temp);
}
}
cout<<-1<<endl;
return;
}
int main()
{
int s,e;
while(1)
{
cin>>n;
if(!n)
break;
for(int i=1;i<=n;i++)
mark[i]=0;
cin>>s>>e;
for(int i=1;i<=n;i++)
cin>>flor[i];
bfs(s,e);
}
return 0;
}
AC代码: 最短路 这里是用Dijkstra 做的
给你楼层和数据 只需要 把对应楼层能到达的楼层建立一条边 权值设为1(管他1,2的 你开心就还 不过 别让最长路径 超过了 那个inf就好) 求出最短路就可以
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxp = 205;
const int inf = 1e6;
int dis[maxp];
int map[maxp][maxp];
int mark[maxp];
int dijkstra(int s,int e,int n)
{
dis[s]=0;
for(int i=1;i<=n;i++)
{
int m=inf,p;
for(int j=1;j<=n;j++)
if(!mark[j]&&dis[j]<m)
m=dis[p=j];
mark[p]=1;
if(dis[p]==inf)
break;
for(int j=1;j<=n;j++)
{
if(map[p][j]<inf&&dis[j]>dis[p]+map[p][j])
dis[j]=dis[p]+map[p][j];
}
}
return dis[e];
}
int main()
{
int n,s,e;
while(1)
{
scanf("%d",&n);
if(n==0)
break;
scanf("%d%d",&s,&e);
int e1,e2;
int temp;
for(int i=1;i<=n;i++)
{
mark[i]=0;
dis[i]=inf;
for(int j=1;j<=n;j++)
{
map[i][j]=inf;
}
}
for(int i=1;i<=n;i++)
{
scanf("%d",&temp);
e1=i+temp;
e2=i-temp;
if(e1<=n&&e1>=1)
map[i][e1]=1;
if(e2>=1&&e2<=n)
map[i][e2]=1;
}
int ds=dijkstra(s,e,n);
if(ds==inf)
cout<<-1<<endl;
else
cout<<ds<<endl;
}
return 0;
}
FINESHED!