CF3A Shortest path of the king
Posted bravewtz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CF3A Shortest path of the king相关的知识,希望对你有一定的参考价值。
The king is left alone on the chessboard. In spite of this loneliness, he doesn‘t lose heart, because he has business of national importance. For example, he has to pay an official visit to square t.
As the king is not in habit of wasting his time, he wants to get from his current position s to square t in
the least number of moves. Help him to do this.
In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to).
Input
The first line contains the chessboard coordinates of square s, the second line — of square t.
Chessboard coordinates consist of two characters, the first one is a lowercase Latin letter (from a to h),
the second one is a digit from 1to 8.
Output
In the first line print n — minimum number of the king‘s moves. Then in n lines
print the moves themselves. Each move is described with one of the 8: L, R, U, D, LU, LD, RU or RD.
L, R, U, D stand
respectively for moves left, right, up and down (according to the picture), and 2-letter combinations stand for diagonal moves. If the answer is not unique, print any of them.
题目大意:从起点走到终点,求最短距离,而且写出最短距离的路径是什么样的:
样例输入:
a8 h1
样例输出:
7 RD RD RD RD RD RD RD
分析:贪心模拟,由题意知道最多有八个可以移动的方向:L,R,U,D,LU,LD,RU,RD,那么当前位置与终点不同就要优先走斜线,模拟一下即可知道最短路径的长度为起点与终点横坐标差的绝对值与纵坐标差的绝对值中较大的那一个。由于走斜线的格式均是
L或R+U或D
,输出移动动作时可以将走斜线分解为横坐标走一步加纵坐标走一步。
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 #include<cstring> 5 #include<cstdlib> 6 using namespace std; 7 string s1,s2;//记录始末位置坐标 8 9 int main(){ 10 char cx,cy; 11 cin>>s1>>s2; 12 int x=s1[0]-s2[0]; 13 int y=s1[1]-s2[1]; 14 cx=x<0?‘R‘:‘L‘; 15 cy=y<0?‘U‘:‘D‘; 16 17 if(x<0){ 18 x=-x; 19 } 20 if(y<0){ 21 y=-y; 22 } 23 printf("%d ",x>y?x:y); 24 25 for( ;x||y; putchar(‘ ‘)){ 26 if(x){ 27 x--; 28 putchar(cx); 29 } 30 if(y){ 31 y--; 32 putchar(cy); 33 } 34 } 35 36 return 0; 37 }
以上是关于CF3A Shortest path of the king的主要内容,如果未能解决你的问题,请参考以下文章
CF3A Shortest path of the king
codeforces- Shortest path of the king
Number of Shortest Paths 最短路的数量
Number of Shortest Paths 最短路的数量