【題解】Codeforces 1296C. Yet Another Walking Robot

【題目敘述】https://codeforces.com/contest/1296/problem/C

#include <iostream>
#include <map>
using namespace std;
#define pii pair<int, int>
 
const int maxn = 200005;
int t, n, a, x, y, mn;
char c;
string str;
pii ans;
map <pii, int> mp;
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> t;
    while (t--){
        cin >> n;
        cin >> str;
        mp.clear();
        mp[{0, 0}] = 0;
        x = 0;
        y = 0;
        ans = {0, 0};
        mn = 1e9;
        for (int i = 1; i <= n; i++){
            c = str[i-1];
            if (c == 'U') x--;
            else if (c == 'D') x++;
            else if (c == 'L') y--;
            else if (c == 'R') y++;
            if (mp.count({x, y})){
                a = mp[{x, y}];
                if (i-a < mn){
                    mn = i-a;
                    ans = {a+1, i};
                }
            }
            mp[{x, y}] = i;
        }
        if (ans.second == 0){
            cout << "-1\n";
            continue;
        }
        cout << ans.first << " " << ans.second << "\n";
    }
}
分享本文 Share with friends