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

本文解析了Codeforces上A.RobotSequence题目,介绍了如何通过记录前缀和来找出所有起点和终点相同的子串的方法。

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;
}

转载于:https://www.cnblogs.com/qscqesze/p/5188832.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值