蛇和梯子 |
Time Limit: 1000ms, Special Time Limit:2500ms, Memory Limit:32768KB |
Total submit users: 5, Accepted users: 4 |
Problem 10103 : No special judgement |
Problem description |
蛇和梯子”是一个在N*N(0 < N ≤ 20)的方格棋盘上进行的游戏。(见下图) 方格从1到N的平方编号。 |
Input |
有多个测试序列。不同测试数据之间用一个空行隔开 每个测试序列第一行包含一个正整数N,表示棋盘大小。如果N=0表示输入结束并且不需要处理。 第二行包含一个整数M,表示梯子的数目。 接下来M行,每行包含两个正整数B,T,表示梯子的底部、顶部。 接下来一行包含一个整数K,表示蛇的数目。 接下来K行,每行包含两个正整数O,L,表示蛇的头尾。 |
Output |
每个测试序列输出一行,包含一个正整数,表示需要最少扔骰子的次数。 |
Sample Input |
6 3 3 23 5 16 20 33 1 35 25 5 1 9 11 1 16 14 0 |
Sample Output |
3 4 |
Judge Tips |
(在上图所示例一中,走4步到达5并由梯子上升到16,再走4步到达20并由梯子上升到33,然后走3步。这样,一共需要扔3次骰子。而在例二中,是连扔4个6。) |
题目的意思很好理解,也是比较典型的BFS。梯子和蛇可以直接变成转换器,其他的和一般的BFS完全一样,只要别忘记标记、剪枝就可以了。
代码如下:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
int x,step;
};
struct N
{
int x,y;
};
N as[405],bs[405];
int n,m,s;
bool flag[405];
int bfs()
{
node st,ed;
queue<node> q;
st.x=1;st.step=0;
q.push(st);
flag[st.x]=1;
while(!q.empty())
{
st=q.front();q.pop();
for(int i=1;i<=6;i++)
{
ed.x=st.x+i;ed.step=st.step+1;
if(ed.x>n*n) break;
for(int j=0;j<m;j++)
if(ed.x==as[j].x)
{
ed.x=as[j].y;
break;
}
for(int j=0;j<s;j++)
if(ed.x==bs[j].x)
{
ed.x=bs[j].y;
break;
}
if(flag[ed.x]==1) continue;
if(ed.x==n*n) return ed.step;
flag[ed.x]=1;
q.push(ed);
}
}
return 0;
}
int main()
{
while(scanf("%d",&n),n)
{
scanf("%d",&m);
for(int i=0;i<m;i++)
scanf("%d%d",&as[i].x,&as[i].y);
scanf("%d",&s);
for(int i=0;i<s;i++)
scanf("%d%d",&bs[i].x,&bs[i].y);
memset(flag,0,sizeof(flag));
int step=bfs();
cout<<step<<endl;
}
return 0;
}