8VC Venture Cup 2016 - Elimination Round A. Robot Sequence 暴力

本文解析了Codeforces上的一道A级题目,介绍了一个简单的算法问题:如何计算字符串中能够使机器人回到起始位置的有效子串数量。通过使用前缀和的方法实现了O(n^2)的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A. Robot Sequence

题目连接:

http://www.codeforces.com/contest/626/problem/A

Description

Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.

Input

The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands.

The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.

Output

Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.

Sample Input

6
URLLDR

Sample Output

2

Hint

题意

给你一个命令,然后让你输出这个命令中有多少个子串的起点和终点是一样的

题解:

数据范围只有200,所以直接n^2暴力就好了

记录一下前缀和。

其实不记录前缀和 n^3也是兹瓷的

代码

#include<bits/stdc++.h>
using namespace std;

const int maxn = 503;
char s[maxn];
int x[maxn],y[maxn];

int main()
{
    int n;
    scanf("%d",&n);
    scanf("%s",s+1);
    for(int i=1;i<=n;i++)
    {
        x[i]=x[i-1];
        y[i]=y[i-1];
        if(s[i]=='U')x[i]++;
        if(s[i]=='D')x[i]--;
        if(s[i]=='L')y[i]++;
        if(s[i]=='R')y[i]--;
    }
    int ans = 0;
    for(int i=0;i<=n;i++)
        for(int j=i+1;j<=n;j++)
            if(x[i]-x[j]==0&&y[i]-y[j]==0)
                ans++;
    cout<<ans<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值