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

被折叠的 条评论
为什么被折叠?



