码迷,mamicode.com
首页 > 其他好文 > 详细

CF3A Shortest path of the king

时间:2019-02-06 23:53:56      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:com   current   general   不同   str   answer   cas   output   位置   

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\n",x>y?x:y);
24 
25     for( ;x||y; putchar(\n)){
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

标签:com   current   general   不同   str   answer   cas   output   位置   

原文地址:https://www.cnblogs.com/Bravewtz/p/10354273.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!