Back and Forth 思维 模拟

题目:

Dolphin resides in two-dimensional Cartesian plane, with the positive x-axis pointing right and the positive y-axis pointing up.
Currently, he is located at the point (sx,sy). In each second, he can move up, down, left or right by a distance of 1.
Here, both the x- and y-coordinates before and after each movement must be integers.
He will first visit the point (tx,ty) where sx<tx and sy<ty, then go back to the point (sx,sy), then visit the point (tx,ty) again, and lastly go back to the point (sx,sy).
Here, during the whole travel, he is not allowed to pass through the same point more than once, except the points (sx,sy) and (tx,ty).
Under this condition, find a shortest path for him.

约束条件:

  • −1000≤sx<tx≤1000
  • −1000≤sy<ty≤1000
  • sx,sy,tx and ty are integers.

输入:

The input is given from Standard Input in the following format:

sx sy tx ty

输出:

Print a string S that represents a shortest path for Dolphin.
The i-th character in S should correspond to his i-th movement.
The directions of the movements should be indicated by the following characters:

  • U: Up
  • D: Down
  • L: Left
  • R: Right

If there exist multiple shortest paths under the condition, print any of them.

样例输入:

0 0 1 2

样例输出:

UURDDLLUUURRDRDDDLLU

One possible shortest path is:

  • Going from (sx,sy) to (tx,ty) for the first time: (0,0) → (0,1) → (0,2) → (1,2)
  • Going from (tx,ty) to (sx,sy) for the first time: (1,2) → (1,1) → (1,0) → (0,0)
  • Going from (sx,sy) to (tx,ty) for the second time: (0,0) → (−1,0) → (−1,1) → (−1,2) → (−1,3) → (0,3) → (1,3) → (1,2)
  • Going from (tx,ty) to (sx,sy) for the second time: (1,2) → (2,2) → (2,1) → (2,0) → (2,−1) → (1,−1) → (0,−1) → (0,0)

第一次做这种模拟题,以前都不清楚模拟是什么。

那么,什么是模拟呢?
就是按照题目给的操作,用代码依次描述出来即可。

对于这个题,借一下图来形容一下这个过程。

 再来看案例,从S往T的时候首先是URDL,所以顺序就是URDL。第二次回到S的时候,因为不能走以前走过的点,所以从S往T走开始只能选择L和D,再根据案例(可以分别试一下两种情况),可知开始要选L。从T往S的时候,由案例可知开始要选R。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
    int sx,sy,tx,ty;
    scanf("%d%d%d%d",&sx,&sy,&tx,&ty);
    for(int i=1;i<=(ty-sy);i++)printf("U");
    for(int i=1;i<=(tx-sx);i++)printf("R");
    for(int i=1;i<=(ty-sy);i++)printf("D");
    for(int i=1;i<=(tx-sx);i++)printf("L");
    printf("L");
    for(int i=1;i<=(ty-sy)+1;i++)printf("U");//这四个判断条件+1是因为事先或时候都多走了一步,所以要走回来
    for(int i=1;i<=(tx-sx)+1;i++)printf("R");
    printf("D");
    printf("R");
    for(int i=1;i<=(ty-sy)+1;i++)printf("D");
    for(int i=1;i<=(tx-sx)+1;i++)printf("L");
    printf("U\n");
    return 0;
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值