A strange lift HDU - 1548 (已AC和未AC版本)
本題我做了兩次,第一次是在出隊的時候進行判斷,如果到達b就返回,第二次是在進隊的時候判斷,如果到達b就返回,但奇怪的是第一次可以提交,第二次的一直WA?,求大佬指點一二
版本1(可以AC)
#include <stdio.h>
#include <string.h>
#include <queue>using namespace std;
typedef struct Node
{
int x, time;
}Node;queue<Node> q;
int list[201];
bool mark[201];int BFS(int a, int b, int c)
{
int up, down;
Node now, tmp;
while(!q.empty())
{
now = q.front();
q.pop();
if(now.x == b) //在出隊的時候判斷,如果到達b就返回
return now.time;
up = now.x + list[now.x];
down = now.x - list[now.x];
if(up <= c && !mark[up])
{
tmp.x = up;
tmp.time = now.time+1;
mark[up] = true;
q.push(tmp);
// if(up == b)
// return tmp.time;
}
if(down >= 1 && !mark[down])
{
tmp.x = down;
tmp.time = now.time+1;
mark[down] = true;
q.push(tmp);
// if(down == b)
// return tmp.time;
}
}
return -1;
}int main()
{
int c, a, b;
while(scanf("%d", &c) && c != 0)
{
scanf("%d %d", &a, &b);
memset(mark, 0, sizeof(mark));
for(int i = 1; i <= c; i++)
scanf("%d", &list[i]);
while(!q.empty())
q.pop();
Node start;
start.x = a;
start.time = 0;
mark[a] = true;
q.push(start);
int ans = BFS(a, b, c);
printf("%d\n", ans);
}
return 0;
}
版本2(未AC)
#include <stdio.h>
#include <string.h>
#include <queue>using namespace std;
typedef struct Node
{
int x, time;
}Node;queue<Node> q;
int list[201];
bool mark[201];int BFS(int a, int b, int c)
{
int up, down;
Node now, tmp;
while(!q.empty())
{
now = q.front();
q.pop();
// if(now.x == b)
// return now.time;
up = now.x + list[now.x];
down = now.x - list[now.x];
if(up <= c && !mark[up])
{
tmp.x = up;
tmp.time = now.time+1;
mark[up] = true;
q.push(tmp);
if(up == b) //入隊的時候進行判斷,如果到達b就返回
return tmp.time;
}
if(down >= 1 && !mark[down])
{
tmp.x = down;
tmp.time = now.time+1;
mark[down] = true;
q.push(tmp);
if(down == b) //同理
return tmp.time;
}
}
return -1;
}int main()
{
int c, a, b;
while(scanf("%d", &c) && c != 0)
{
scanf("%d %d", &a, &b);
memset(mark, 0, sizeof(mark));
for(int i = 1; i <= c; i++)
scanf("%d", &list[i]);
while(!q.empty())
q.pop();
Node start;
start.x = a;
start.time = 0;
mark[a] = true;
q.push(start);
int ans = BFS(a, b, c);
printf("%d\n", ans);
}
return 0;
}