Here comes the problem: when you are on floor A,and you want to go to floor B,how many times at least he has to press the button "UP" or "DOWN"?
The first line contains three integers N ,A,B( 1 <= N,A,B <= 200) which describe above,The second line consist N integers k1,k2,....kn.
A single 0 indicate the end of the input. OutputFor each case of the input output a interger, the least times you have to press the button when you on floor A,and you want to go to floor B.If you can't reach floor B,printf "-1". Sample Input
5 1 5 3 3 1 2 5 0Sample Output
3
解題思路:
這道題雖然就是一個bfs,開始的時候也是正常寫,但是沒有做vis標記,當時不覺得需要用vis(但是實際上是需要的,因爲如果重複走了一個臺階的話,就不是最優的情況了,雖然能得出答案)交了之後,就mle,於是加了限制條件剪枝,但是沒有考慮清楚加錯了,最後還是老實加了vis數組,其實就是一個很簡單的題目,一直想偏,一直也過不了
代碼:
#include<iostream>
#include<cstring>
#include<queue>
#include<cmath>
using namespace std;
int n,beginn,endd;
struct node
{
int pos;
int go;
int num;
};
node a[250];
int vis[250];
int bfs(node now)
{
queue<node> q;
q.push(now);
vis[now.pos] = 1;
node help;
node help1;
node help2;
while(!q.empty())
{
// cout<<"here"<<endl;
help = q.front();
q.pop();
if(help.pos==endd)
return help.num;
help1.pos = help.pos+help.go;
if(help1.pos==endd)
return help.num+1;
if(help1.pos>=1&&help1.pos<=n&&!vis[help1.pos])
{
help1.go = a[help1.pos].go;
help1.num = help.num+1;
q.push(help1);
vis[help1.pos] = 1;
}
help2.pos = help.pos-help.go;
if(help2.pos==endd)
return help.num+1;
if(help2.pos>=1&&help2.pos<=n&&!vis[help2.pos])
{
// cout<<"here"<<endl;
help2.go = a[help2.pos].go;
help2.num = help.num+1;
q.push(help2);
vis[help2.pos] = 1;
}
}
return -1;
}
int main()
{
while(cin>>n)
{
memset(vis,0,sizeof(vis));
if(n==0)
break;
cin>>beginn;
cin>>endd;
for(int i = 1;i<=n;i++)
{
cin>>a[i].go;
a[i].pos = i;
a[i].num = 0;
}
node c;
c.go = a[beginn].go;
c.pos = beginn;
c.num = 0;
int re = bfs(c);
cout<<re<<endl;
}
}