小白进阶之路---CF1296C--Yet Another Walking Robot

 

又被虐了,居然还以为是尺取法或者前缀,长记性吧

 

 

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #include<cmath>
 5 #include<stack>
 6 #include<queue>
 7 #include<map> 
 8 #include<list>
 9 #include<string>
10 #include<cstring>
11 #include<set>
12 #include<vector>
13 #define ll long long
14 #define memset(a,n) memset(a,n,sizeof(a))
15 #define mp make_pair 
16 #define pb push_back
17 using namespace std;
18 const int maxn = 1e5 + 100;
19 
20 map<pair<int,int>,int> mapp;// 坐标 -> 到该位置的时间 
21 
22 
23 
24 // 思考:我原来的思路: 寻找字符串最短长度内L = R,U = D (数量)  O(n * n)
25 // 现在的思路 :记录机器人行走的位置和到达该位置的时间,如果来过这个位置,就及时维护最小值,否则继续模拟机器人行走 
26 // 因为map中记录的是第一次到达该位置的时间,所以保证能使长度最小 
27 
28 
29 void solve( )
30 {
31     mapp.clear();
32     int n;string s;cin >> n >>  s;
33     int x = 0,y = 0; // 当前坐标
34     int L = 0,R = 1e9; 
35     for(int i = 0 ; i <= n;i++){
36         if(mapp.count(mp(x,y))){ //  如果这个位置已经来到过了 
37             int cur_l = mapp[mp(x,y)];
38             int cur_r = i;
39             if(R - L > cur_r - cur_l){ // 并且当前长度比 当前节点的重复最小长度短就更换最小值 
40                 R = cur_r;L = cur_l;
41             }
42         }
43         if(i == n) break;
44         mapp[mp(x,y)] = i + 1;// 记录路径次序 
45         if(s[i] == 'L'){ // 模拟移动路径 
46             --x;
47         }else if(s[i] == 'R'){
48             ++x;
49         }else if(s[i] == 'U'){
50             ++y;
51         }else if(s[i] == 'D'){
52             --y;
53         }
54     }
55     if(L == 0){
56         cout << "-1\n";
57     }else{
58         cout << L << " " << R << endl;
59     }
60 }
61 
62 
63 int main()
64 {
65     ios::sync_with_stdio(0);
66     int t ;cin >> t;
67     while(t--){
68         solve();
69     } 
70     return 0;
71 }

 

posted @ 2020-04-17 22:48  Wise_4  阅读(132)  评论(0编辑  收藏  举报