給你一個字符串,代表機器人的行動方向,請你刪除這個字符串的一個子串,使機器人終點並不改變,有多個子串滿足條件時,輸出最短的那個。
就是找字符串中機器人軌跡最短的重複。
設置從開始,記錄每一步的座標以及第幾步step扔進一個結構體,排序後統計。如果是同一位置就是相同,比較它們step差多少,就是刪去子串的長度,更新答案即可。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
#define ms(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
typedef double ab;
const int N=1e6+10;
string s;
struct node
{
int x,y,step;
bool operator < (const node A) const
{
if(x==A.x&&y==A.y) return step>A.step;
if(x==A.x) return y>A.y;
return x>A.x;
}
};
priority_queue<node>q;
int main()
{
int n,t;
cin>>t;
while(t--)
{
cin>>n>>s;
int x=0,y=0;
q.empty();
q.push({x,y,0});
for(int i=0;i<n;i++)
{
if(s[i]=='L') --y;
if(s[i]=='R') ++y;
if(s[i]=='U') --x;
if(s[i]=='D') ++x;
q.push({x,y,i+1});
}
int ans=INF,l,r;
node pre={-INF,-INF,-INF};
while(!q.empty())
{
node tmp=q.top();
q.pop();
if(tmp.x==pre.x&&tmp.y==pre.y)
{
if(tmp.step-pre.step<ans)
{
l=pre.step+1;
r=tmp.step;
ans=tmp.step-pre.step;
}
}
pre=tmp;
}
if(ans==INF) cout<<"-1"<<endl;
else cout<<l<<" "<<r<<endl;
}
//system("pause");
}