CF626A Robot Sequence 题解

· · 题解

题目大意

随意输入了一串指令,求有多少个指令子段能使机器人回到原点。

具体思路

把整个操作系统看成一个直角坐标系,机器人向上走,则 x 坐标增加一,向下走,则 x 坐标减少一。以此类推,最后只需要把这个过程模拟出来就行了。

AC Code

#include <bits/stdc++.h>
#define ll long long
#define rint register int  
#define For(i,l,r) for(rint i=l;i<=r;i++)
#define FOR(i,r,l) for(rint i=r;i>=l;i--)
#define mod 1000000007
using namespace std;

inline int read() {
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
    return x*f;
}

const int N = 205;

char s[N];

int n, ans;

signed main() {
    n = read();
    scanf("%s", s + 1);
    For(i,1,n) {
        For(j,i,n) {
            int x, y;
            x = y = 0;
            For(k,i,j) {
                if(s[k] == 'U') x ++;
                if(s[k] == 'D') x --;
                if(s[k] == 'L') y --;
                if(s[k] == 'R') y ++; 
            }
            ans += x == 0 && y == 0;
        }
    }
    cout << ans << '\n';
    return 0;
} 
但还不够优美,仔细想一下,可省了内层枚举。 # AC Code ```cpp #include <bits/stdc++.h> #define ll long long #define rint register int #define For(i,l,r) for(rint i=l;i<=r;i++) #define FOR(i,r,l) for(rint i=r;i>=l;i--) #define mod 1000000007 using namespace std; inline int read() { int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();} return x*f; } const int N = 205; char s[N]; int n, ans; signed main() { n = read(); scanf("%s", s + 1); For(i,1,n) { int x, y; x = y = 0; For(j,i,n) { if(s[j] == 'U') x ++; if(s[j] == 'D') x --; if(s[j] == 'L') y --; if(s[j] == 'R') y ++; ans += x == 0 && y == 0; } } cout << ans << '\n'; return 0; } ``` $O(N^2)$,完美收官!