Codeforce 1296 C. Yet Another Walking Robot

给你一个字符串,代表机器人的行动方向,请你删除这个字符串的一个子串,使机器人终点并不改变,有多个子串满足条件时,输出最短的那个。

就是找字符串中机器人轨迹最短的重复。

设置从\left ( 0,0 \right )开始,记录每一步的坐标\left ( x,y \right )以及第几步step扔进一个结构体,排序后统计。如果是同一位置就是\left ( x,y \right )相同,比较它们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");
}

猜你喜欢

转载自blog.csdn.net/Luowaterbi/article/details/104183721