cf1607 Round #753 Div3-E【构造】

本文介绍了一种在n*m棋盘上寻找最长路径的操作算法。通过动态调整四个方向的步数,实现最大步数下的起点定位。代码示例使用C++实现,并详细解释了算法流程。

Date:2022.01.14
题意:n*m的棋盘,给定操作序列,找到操作次数不出棋盘的最大步数下的起点。
在这里插入图片描述

思路:记录四个方向的最大步数方法如下:
①像一个方向走一步,先判断反方向的步数是否是正的,若是反方向先-1,直到反方向为0,本方向+1。
②每步记录每个方向的最大步数。
特别注意,如果两个正反方向的最大步数均为0,则若为左右方向则以m为起点;若为上下方向则以n为起点。
代码如下:

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e6+10;
typedef long long LL;
LL n,m,t,k;
char c[N];
int main()
{
    cin>>t;
    while(t--)
    {
        cin>>n>>m;string s;cin>>s;
        LL i=0;
        LL l=0,r=0,u=0,d=0;LL maxl=0,maxr=0,maxu=0,maxd=0;
        while(maxl+maxr+1<=m && maxu+maxd+1<=n && i<s.length())
        {
            if(s[i]=='L') 
            {
                if(r>0) r--;
                else if(r==0) l++;
                if(l>maxl)
                {
                    if(l+maxr+1<=m) maxl=max(maxl,l);
                    else break;
                }
            }
            else if(s[i]=='R') 
            {
                if(l>0) l--;
                else if(l==0) r++;
                if(r>maxr)
                {
                    if(r+maxl+1<=m) maxr=max(maxr,r);
                    else break;
                }
            }
            else if(s[i]=='U') 
            {
                if(d>0) d--;
                else if(d==0) u++;
                if(u>maxu)
                {
                    if(u+maxd+1<=n) maxu=max(maxu,u);
                    else break;
                }
            }
            else if(s[i]=='D') 
            {
                if(u>0) u--;
                else if(u==0) d++;
                if(d>maxd)
                {
                    if(d+maxu+1<=n) maxd=max(maxd,d);
                    else break;
                }
            }
            i++;
        }
        if(maxu>0) cout<<maxu+1<<' ';
        else if(maxd>0) cout<<n-maxd<<' ';
        else if(maxu==0 && maxd==0) cout<<n<<' ';
        if(maxl>0) cout<<maxl+1<<' ';
        else if(maxr>0) cout<<m-maxr<<' ';
        else if(maxr==0 && maxl==0) cout<<m<<' ';
        cout<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值